Skip to content

Commit 9c45ee5

Browse files
authored
Merge pull request #1846 from cuthbertLab/pyupgrader-upgrades
Prepare Music21 to run on Ruff
2 parents 319de08 + 36330e5 commit 9c45ee5

File tree

112 files changed

+839
-642
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

112 files changed

+839
-642
lines changed

.pylintrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ init-import=no
290290

291291
# A regular expression matching the name of dummy variables (i.e. expectedly
292292
# not used).
293-
dummy-variables-rgx=_$|dummy|unused|i$|j$|junk|counter
293+
dummy-variables-rgx=_|dummy|unused|i$|j$|junk|counter
294294

295295
# List of additional names supposed to be defined in builtins. Remember that
296296
# you should avoid to define new builtins when possible.

documentation/docbuild/documenters.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -538,8 +538,11 @@ def _formatInheritedMembersMapping(self, mapping, banner):
538538
for classDocumenter in self.baseClassDocumenters:
539539
if classDocumenter not in mapping:
540540
continue
541-
result.append(banner.format(
542-
classDocumenter.rstCrossReferenceString))
541+
result.append(
542+
banner.format(
543+
classDocumenter.rstCrossReferenceString
544+
)
545+
)
543546
result.append('')
544547
memberDocumenters = mapping[classDocumenter]
545548
result.append('.. hlist::')
@@ -757,10 +760,9 @@ def inheritedReadwritePropertiesMapping(self):
757760
>>> mapping = documenter.inheritedReadwritePropertiesMapping
758761
>>> sortBy = lambda x: x.referentPackageSystemPath
759762
>>> for classDocumenter in sorted(mapping, key=sortBy):
760-
... print('{0}:'.format(classDocumenter.referentPackageSystemPath))
763+
... print(f'{classDocumenter.referentPackageSystemPath}:')
761764
... for attributeDocumenter in mapping[classDocumenter][:10]:
762-
... print('- {0}'.format(attributeDocumenter.referentPackageSystemPath))
763-
...
765+
... print(f'- {attributeDocumenter.referentPackageSystemPath}')
764766
music21.base.Music21Object:
765767
- music21.base.Music21Object.activeSite
766768
- music21.base.Music21Object.derivation
@@ -940,13 +942,10 @@ def rstInheritedDocAttrFormat(self):
940942
result.append('.. hlist::')
941943
result.append(' :columns: 3')
942944
result.append('')
943-
formatString = ' - :attr:`~{0}.{1}`'
945+
basePath = baseDocumenter.referentPackageSystemPath
944946
for attrName in attrNames:
945947
result.append(
946-
formatString.format(
947-
baseDocumenter.referentPackageSystemPath,
948-
attrName,
949-
)
948+
f' - :attr:`~{basePath}.{attrName}`'
950949
)
951950
result.append('')
952951
return result
@@ -1594,14 +1593,15 @@ def getRstComposerWorksFormat(self, corpusWork):
15941593

15951594
# def getRstVirtualWorkFileDictFormat(self, corpusFile):
15961595
# result = []
1597-
# result.append('- {0} *({1})*: `{2}`'.format(
1598-
# str(corpusFile.title),
1599-
# str(corpusFile.format),
1600-
# str(corpusFile.path),
1601-
# ))
1596+
# result.append(
1597+
# f'- {corpusFile.title} '
1598+
# f'*({corpusFile.format})*: '
1599+
# f'`{corpusFile.path}`'
1600+
# )
16021601
# result.append('')
1603-
# result.append(' Source: {0}'.format(
1604-
# str(corpusFile.url)))
1602+
# result.append(
1603+
# f' Source: {corpusFile.url}'
1604+
# )
16051605
# result.append('')
16061606
# return result
16071607

documentation/source/developerReference/developerGuidelines.ipynb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,17 @@
145145
"Conventions:\n",
146146
"\n",
147147
" - **Strings MUST be 'single-quoted', but \"double quotes\" are allowed internally**\n",
148-
" - This rule applies to triple quotes and doc strings also, contrary to PEP 257.\n",
149-
" - Docstrings must begin and end on their own lines. No one-line doc-strings or text\n",
148+
" - This rule applies to triple quotes and docstrings also, contrary to PEP 257.\n",
149+
" - Docstrings must begin and end on their own lines. No one-line docstrings or text\n",
150150
" immediately following the triple quotes.\n",
151151
" - When there is a hyphen or single quote in the string, double quotes should be used,\n",
152152
" not escaping/backslashing.\n",
153153
" - For long streams of TinyNotation or Lilypond code, which both use single quotes to indicate octave,\n",
154154
" triple single quotes around the string are better than double quotes. Internal whitespace\n",
155155
" rarely matters in those formats.\n",
156+
" - Before v10 concatenating strings without a plus sign was discouraged. I've changed my mind,\n",
157+
" and am \"letting Python be Python\" now especially when three or more lines are involved.\n",
158+
" However, use a + sign if concatenation is mixed with different comma-separated arguments.\n",
156159
" - Documentation should follow quoting in American English grammar when not\n",
157160
" discussing code. So for instance, a quotation in documentation is in double quotes.\n",
158161
" - Variable names:\n",
@@ -163,7 +166,8 @@
163166
" - Line lengths are capped at 100, but if approaching this limit, look for ways to avoid one-lining.\n",
164167
" - if it's easy to split your line into two which are both under 80 characters, do so.\n",
165168
" - Line continuation characters (`\\`) are not allowed; use open parentheses.\n",
166-
" - Prefer f-strings to `.format()`. The `%` interpolation is no longer allowed.\n",
169+
" - Greatly prefer f-strings to `.format()`. The `%` interpolation is no longer allowed.\n",
170+
" - `.format()` is only to be used when a repeated format string is involved.\n",
167171
" - Annotating types is **required** in new code, and encouraged to be added to older code.\n",
168172
" - e.g. `self.counter: int = 0` or `def makeNoises() -> list['noise.Noise']:`\n",
169173
" - The typing library should always be imported as `t`.\n",
@@ -193,7 +197,8 @@
193197
" manipulation of the original object. When `inPlace` is True, nothing should be returned\n",
194198
" (not true for `music21j` since passing through objects is so expected in JavaScript thanks\n",
195199
" to JQuery and other libraries). Use the `@overload` decorator to show how this parameter\n",
196-
" affects the return value -- Python makes this a bit hard, but see for instance, :meth:`~music21.stream.base.Stream.getElementsByClass` for an example of how to use this.\n",
200+
" affects the return value -- Python makes this a bit hard, but see for\n",
201+
" instance, :meth:`~music21.stream.base.Stream.getElementsByClass` for an example of how to use this.\n",
197202
" - Use descriptive pull request titles (rather than GitHub's default \"Update pitch.py\")\n",
198203
" - Do not have a PR title so long that it cannot be seen in one line. Simplify and\n",
199204
" rewrite and go into more detail in the description. I depend on skimming PR titles\n",

music21/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,16 @@
167167
'voiceLeading',
168168
'volpiano',
169169
'volume',
170+
171+
'Music21Exception',
172+
'SitesException',
173+
'Music21ObjectException',
174+
'ElementException',
175+
176+
'Groups',
177+
'Music21Object',
178+
'ElementWrapper',
179+
'VERSION',
170180
]
171181

172182
# ------------------------------------------------------------------------------

music21/abcFormat/__init__.py

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2621,7 +2621,7 @@ def tokenProcess(self) -> None:
26212621
else:
26222622
environLocal.printDebug(
26232623
['broken rhythm marker '
2624-
+ f'({token.src}) not positioned between two notes or chords'])
2624+
f'({token.src}) not positioned between two notes or chords'])
26252625

26262626
# need to update tuplets with currently active meter
26272627
if isinstance(token, ABCTuplet):
@@ -2698,7 +2698,7 @@ def tokenProcess(self) -> None:
26982698
if lastDefaultQL is None:
26992699
raise ABCHandlerException(
27002700
'no active default note length provided for note processing. '
2701-
+ f'tPrev: {tPrev}, token: {token}, tNext: {tNext}'
2701+
f'tPrev: {tPrev}, token: {token}, tNext: {tNext}'
27022702
)
27032703
token.activeDefaultQuarterLength = lastDefaultQL
27042704
token.activeKeySignature = lastKeySignature
@@ -3671,21 +3671,22 @@ def testSplitByMeasure(self):
36713671
ah.process(testFiles.hectorTheHero)
36723672
ahm = ah.splitByMeasure()
36733673

3674-
for i, l, r in [(0, None, None), # metadata
3675-
(2, '|:', '|'),
3676-
(3, '|', '|'),
3677-
(-2, '[1', ':|'),
3678-
(-1, '[2', '|'),
3679-
]:
3680-
if l is None:
3674+
for i, left, right in [
3675+
(0, None, None), # metadata
3676+
(2, '|:', '|'),
3677+
(3, '|', '|'),
3678+
(-2, '[1', ':|'),
3679+
(-1, '[2', '|'),
3680+
]:
3681+
if left is None:
36813682
self.assertEqual(ahm[i].leftBarToken, None)
36823683
else:
3683-
self.assertEqual(ahm[i].leftBarToken.src, l)
3684+
self.assertEqual(ahm[i].leftBarToken.src, left)
36843685

3685-
if r is None:
3686+
if right is None:
36863687
self.assertEqual(ahm[i].rightBarToken, None)
36873688
else:
3688-
self.assertEqual(ahm[i].rightBarToken.src, r)
3689+
self.assertEqual(ahm[i].rightBarToken.src, right)
36893690

36903691
# for ahSub in ah.splitByMeasure():
36913692
# environLocal.printDebug(['split by measure:', ahSub.tokens])
@@ -3696,37 +3697,39 @@ def testSplitByMeasure(self):
36963697
ah.process(testFiles.theBeggerBoy)
36973698
ahm = ah.splitByMeasure()
36983699

3699-
for i, l, r in [(0, None, None), # metadata
3700-
(1, None, '|'),
3701-
(-1, '||', None), # trailing lyric metadata
3702-
]:
3703-
if l is None:
3700+
for i, left, right in [
3701+
(0, None, None), # metadata
3702+
(1, None, '|'),
3703+
(-1, '||', None), # trailing lyric metadata
3704+
]:
3705+
if left is None:
37043706
self.assertEqual(ahm[i].leftBarToken, None)
37053707
else:
3706-
self.assertEqual(ahm[i].leftBarToken.src, l)
3708+
self.assertEqual(ahm[i].leftBarToken.src, left)
37073709

3708-
if r is None:
3710+
if right is None:
37093711
self.assertEqual(ahm[i].rightBarToken, None)
37103712
else:
3711-
self.assertEqual(ahm[i].rightBarToken.src, r)
3713+
self.assertEqual(ahm[i].rightBarToken.src, right)
37123714

37133715
# test a simple string with no bars
37143716
ah = ABCHandler()
37153717
ah.process('M:6/8\nL:1/8\nK:G\nc1D2')
37163718
ahm = ah.splitByMeasure()
37173719

3718-
for i, l, r in [(0, None, None), # metadata
3719-
(-1, None, None), # note data, but no bars
3720-
]:
3721-
if l is None:
3720+
for i, left, right in [
3721+
(0, None, None), # metadata
3722+
(-1, None, None), # note data, but no bars
3723+
]:
3724+
if left is None:
37223725
self.assertEqual(ahm[i].leftBarToken, None)
37233726
else:
3724-
self.assertEqual(ahm[i].leftBarToken.src, l)
3727+
self.assertEqual(ahm[i].leftBarToken.src, left)
37253728

3726-
if r is None:
3729+
if right is None:
37273730
self.assertEqual(ahm[i].rightBarToken, None)
37283731
else:
3729-
self.assertEqual(ahm[i].rightBarToken.src, r)
3732+
self.assertEqual(ahm[i].rightBarToken.src, right)
37303733

37313734
def testMergeLeadingMetaData(self):
37323735
from music21.abcFormat import testFiles

music21/analysis/correlate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def pitchToDynamic(self, dataPoints=True):
131131
dstCheck = self.streamObj.recurse().getElementsByClass(objName)
132132
if not dstCheck:
133133
raise CorrelateException('cannot create correlation: an object '
134-
+ f'that is not found in the Stream: {objName}')
134+
f'that is not found in the Stream: {objName}')
135135

136136
self._findActive(objNameSrc, objNameDst)
137137

music21/analysis/metrical.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def labelBeatDepth(streamIn):
4343
>>> sOut = []
4444
>>> for n in s.flatten().notes:
4545
... stars = "".join([l.text for l in n.lyrics])
46-
... sOut.append("{0:8s} {1}".format(n.beatStr, stars))
46+
... sOut.append(f'{n.beatStr:8s} {stars}')
4747
>>> print("\n".join(sOut))
4848
1 ****
4949
1 1/2 *

music21/analysis/pitchAnalysis.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def pitchAttributeCount(s, pitchAttr='name'):
2121
>>> bach = corpus.parse('bach/bwv324.xml')
2222
>>> pcCount = analysis.pitchAnalysis.pitchAttributeCount(bach, 'pitchClass')
2323
>>> for n in sorted(pcCount):
24-
... print("%2d: %2d" % (n, pcCount[n]))
24+
... print(f'{n:2d}: {pcCount[n]:2d}')
2525
0: 3
2626
2: 26
2727
3: 3
@@ -36,15 +36,15 @@ def pitchAttributeCount(s, pitchAttr='name'):
3636
3737
>>> nameCount = analysis.pitchAnalysis.pitchAttributeCount(bach, 'name')
3838
>>> for n, count in nameCount.most_common(3):
39-
... print("%2s: %2d" % (n, nameCount[n]))
39+
... print(f'{n:>2s}: {nameCount[n]:2d}')
4040
D: 26
4141
A: 17
4242
F#: 15
4343
4444
4545
>>> nameOctaveCount = analysis.pitchAnalysis.pitchAttributeCount(bach, 'nameWithOctave')
4646
>>> for n in sorted(nameOctaveCount):
47-
... print("%3s: %2d" % (n, nameOctaveCount[n]))
47+
... print(f'{n:>3s}: {nameOctaveCount[n]:2d}')
4848
A2: 2
4949
A3: 5
5050
A4: 10

music21/analysis/reduceChords.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ def computeMeasureChordWeights(
320320
>>> cr = analysis.reduceChords.ChordReducer()
321321
>>> cws = cr.computeMeasureChordWeights(s)
322322
>>> for pcs in sorted(cws):
323-
... print("%18r %2.1f" % (pcs, cws[pcs]))
323+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
324324
(0, 4, 7) 3.0
325325
(0, 11, 4, 5) 1.0
326326
@@ -329,7 +329,7 @@ def computeMeasureChordWeights(
329329
>>> cws = cr.computeMeasureChordWeights(s,
330330
... weightAlgorithm=cr.quarterLengthBeatStrength)
331331
>>> for pcs in sorted(cws):
332-
... print("%18r %2.1f" % (pcs, cws[pcs]))
332+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
333333
(0, 4, 7) 2.2
334334
(0, 11, 4, 5) 0.5
335335
@@ -338,7 +338,7 @@ def computeMeasureChordWeights(
338338
>>> cws = cr.computeMeasureChordWeights(s,
339339
... weightAlgorithm=cr.quarterLengthBeatStrengthMeasurePosition)
340340
>>> for pcs in sorted(cws):
341-
... print("%18r %2.1f" % (pcs, cws[pcs]))
341+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
342342
(0, 4, 7) 3.0
343343
(0, 11, 4, 5) 0.5
344344
@@ -347,7 +347,7 @@ def computeMeasureChordWeights(
347347
>>> cws = cr.computeMeasureChordWeights(s,
348348
... weightAlgorithm=cr.qlbsmpConsonance)
349349
>>> for pcs in sorted(cws):
350-
... print("%18r %2.1f" % (pcs, cws[pcs]))
350+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
351351
(0, 4, 7) 3.0
352352
(0, 11, 4, 5) 0.1
353353
'''

music21/analysis/reduceChordsOld.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,15 +159,15 @@ def computeMeasureChordWeights(self, measureObj, weightAlgorithm=None):
159159
>>> cr = analysis.reduceChordsOld.ChordReducer()
160160
>>> cws = cr.computeMeasureChordWeights(s)
161161
>>> for pcs in sorted(cws):
162-
... print("%18r %2.1f" % (pcs, cws[pcs]))
162+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
163163
(0, 4, 7) 3.0
164164
(0, 11, 4, 5) 1.0
165165
166166
Add beatStrength:
167167
168168
>>> cws = cr.computeMeasureChordWeights(s, weightAlgorithm=cr.quarterLengthBeatStrength)
169169
>>> for pcs in sorted(cws):
170-
... print("%18r %2.1f" % (pcs, cws[pcs]))
170+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
171171
(0, 4, 7) 2.2
172172
(0, 11, 4, 5) 0.5
173173
@@ -176,15 +176,15 @@ def computeMeasureChordWeights(self, measureObj, weightAlgorithm=None):
176176
>>> cws = cr.computeMeasureChordWeights(s,
177177
... weightAlgorithm=cr.quarterLengthBeatStrengthMeasurePosition)
178178
>>> for pcs in sorted(cws):
179-
... print("%18r %2.1f" % (pcs, cws[pcs]))
179+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
180180
(0, 4, 7) 3.0
181181
(0, 11, 4, 5) 0.5
182182
183183
Make consonance count a lot:
184184
185185
>>> cws = cr.computeMeasureChordWeights(s, weightAlgorithm=cr.qlbsmpConsonance)
186186
>>> for pcs in sorted(cws):
187-
... print("%18r %2.1f" % (pcs, cws[pcs]))
187+
... print(f'{pcs!r:18} {cws[pcs]:2.1f}')
188188
(0, 4, 7) 3.0
189189
(0, 11, 4, 5) 0.5
190190
'''

0 commit comments

Comments
 (0)