From 1cbc2a8dd74736b2656e976aa7c51d3c0aeb7a34 Mon Sep 17 00:00:00 2001 From: Michael Scott Asato Cuthbert Date: Tue, 2 Jan 2024 23:46:48 -1000 Subject: [PATCH 1/3] Styleguide Change - Union types From now on, music21 prefers (but does not enforce) no space around union type operator: `|` --- .flake8 | 2 + documentation/testDocumentation.py | 2 +- music21/abcFormat/__init__.py | 98 ++++---- music21/abcFormat/translate.py | 14 +- music21/alpha/analysis/fixer.py | 6 +- music21/alpha/analysis/ornamentRecognizer.py | 6 +- music21/analysis/discrete.py | 22 +- music21/analysis/harmonicFunction.py | 6 +- music21/analysis/reduction.py | 4 +- music21/analysis/windowed.py | 6 +- music21/articulations.py | 4 +- music21/audioSearch/__init__.py | 4 +- music21/bar.py | 8 +- music21/base.py | 108 ++++----- music21/beam.py | 6 +- music21/braille/segment.py | 24 +- music21/braille/translate.py | 20 +- music21/capella/fromCapellaXML.py | 4 +- music21/chord/__init__.py | 88 ++++---- music21/clef.py | 10 +- music21/common/classTools.py | 2 +- music21/common/fileTools.py | 2 +- music21/common/formats.py | 2 +- music21/common/misc.py | 2 +- music21/common/numberTools.py | 20 +- music21/common/pathTools.py | 12 +- music21/common/types.py | 8 +- music21/common/weakrefTools.py | 4 +- music21/converter/__init__.py | 62 ++--- music21/converter/museScore.py | 6 +- music21/converter/subConverters.py | 76 +++---- music21/corpus/__init__.py | 12 +- music21/corpus/chorales.py | 8 +- music21/corpus/corpora.py | 12 +- music21/corpus/manager.py | 24 +- music21/derivation.py | 26 +-- music21/duration.py | 62 ++--- music21/environment.py | 6 +- music21/expressions.py | 226 +++++++++---------- music21/features/base.py | 2 +- music21/features/native.py | 2 +- music21/figuredBass/notation.py | 14 +- music21/figuredBass/resolution.py | 2 +- music21/figuredBass/segment.py | 16 +- music21/freezeThaw.py | 4 +- music21/graph/__init__.py | 2 +- music21/graph/findPlot.py | 6 +- music21/graph/plot.py | 2 +- music21/graph/primitives.py | 4 +- music21/harmony.py | 24 +- music21/humdrum/spineParser.py | 10 +- music21/instrument.py | 34 +-- music21/interval.py | 110 ++++----- music21/key.py | 32 +-- music21/layout.py | 70 +++--- music21/lily/lilyObjects.py | 2 +- music21/lily/translate.py | 4 +- music21/mei/base.py | 10 +- music21/metadata/__init__.py | 74 +++--- music21/metadata/bundles.py | 8 +- music21/metadata/primitives.py | 102 ++++----- music21/metadata/properties.py | 6 +- music21/meter/base.py | 8 +- music21/meter/core.py | 4 +- music21/meter/tools.py | 2 +- music21/midi/__init__.py | 18 +- music21/midi/translate.py | 56 ++--- music21/musicxml/archiveTools.py | 4 +- music21/musicxml/helpers.py | 10 +- music21/musicxml/m21ToXml.py | 92 ++++---- music21/musicxml/partStaffExporter.py | 12 +- music21/musicxml/testPrimitive.py | 4 +- music21/musicxml/xmlSoundParser.py | 4 +- music21/musicxml/xmlToM21.py | 108 ++++----- music21/note.py | 74 +++--- music21/noteworthy/binaryTranslate.py | 2 +- music21/percussion.py | 4 +- music21/pitch.py | 106 ++++----- music21/prebase.py | 6 +- music21/repeat.py | 2 +- music21/roman.py | 48 ++-- music21/romanText/clercqTemperley.py | 18 +- music21/romanText/translate.py | 4 +- music21/romanText/tsvConverter.py | 30 +-- music21/romanText/writeRoman.py | 12 +- music21/scale/__init__.py | 50 ++-- music21/scale/intervalNetwork.py | 138 +++++------ music21/scale/scala/__init__.py | 2 +- music21/search/base.py | 6 +- music21/search/lyrics.py | 14 +- music21/serial.py | 12 +- music21/sieve.py | 14 +- music21/sites.py | 6 +- music21/spanner.py | 28 +-- music21/stream/base.py | 144 ++++++------ music21/stream/core.py | 10 +- music21/stream/filters.py | 2 +- music21/stream/iterator.py | 34 +-- music21/stream/makeNotation.py | 64 +++--- music21/style.py | 38 ++-- music21/tablature.py | 4 +- music21/tempo.py | 26 +-- music21/test/multiprocessTest.py | 4 +- music21/test/testSingleCoreAll.py | 2 +- music21/text.py | 2 +- music21/tinyNotation.py | 4 +- music21/tree/core.py | 2 +- music21/tree/fromStream.py | 24 +- music21/tree/spans.py | 14 +- music21/tree/trees.py | 6 +- music21/tree/verticality.py | 8 +- music21/variant.py | 6 +- music21/voiceLeading.py | 30 +-- music21/volume.py | 6 +- 114 files changed, 1442 insertions(+), 1440 deletions(-) diff --git a/.flake8 b/.flake8 index e24575d3e6..b3d87d545c 100644 --- a/.flake8 +++ b/.flake8 @@ -4,6 +4,8 @@ ignore= E127, # under indented E128, + # space around | -- nice to omit in int|str + E227, # 0 blank lines -- good test but something going wrong in new algorithm E301, # blank lines diff --git a/documentation/testDocumentation.py b/documentation/testDocumentation.py index a8b9b6497f..4d9d97e12f 100644 --- a/documentation/testDocumentation.py +++ b/documentation/testDocumentation.py @@ -191,7 +191,7 @@ def getDocumentationFiles(runOne=False): return allModules -def main(runOne: str | bool = False): +def main(runOne: str|bool = False): if runOne is False: nbvalNotebook.runAll() elif '.ipynb' in runOne: diff --git a/music21/abcFormat/__init__.py b/music21/abcFormat/__init__.py index d0d9646626..b026887c2f 100644 --- a/music21/abcFormat/__init__.py +++ b/music21/abcFormat/__init__.py @@ -116,7 +116,7 @@ # store a mapping of ABC representation to pitch values # key is (srcStr, carriedAccidental, str(keySignature) # value is (pitchName (m21), accidentalDisplayStatus) -_pitchTranslationCache: dict[tuple[str, str, str], tuple[str, bool | None]] = {} +_pitchTranslationCache: dict[tuple[str, str, str], tuple[str, bool|None]] = {} # ------------------------------------------------------------------------------ @@ -372,7 +372,7 @@ def isTempo(self) -> bool: return True return False - def getTimeSignatureParameters(self) -> tuple[int, int, str] | None: + def getTimeSignatureParameters(self) -> tuple[int, int, str]|None: ''' If there is a time signature representation available, get a numerator, denominator and an abbreviation symbol. @@ -424,7 +424,7 @@ def getTimeSignatureParameters(self) -> tuple[int, int, str] | None: symbol = 'normal' # m21 compat return n, d, symbol - def getTimeSignatureObject(self) -> meter.TimeSignature | None: + def getTimeSignatureObject(self) -> meter.TimeSignature|None: ''' Return a music21 :class:`~music21.meter.TimeSignature` object for this metadata tag, if isMeter is True, otherwise raise exception. @@ -458,7 +458,7 @@ def getTimeSignatureObject(self) -> meter.TimeSignature | None: numerator, denominator, unused_symbol = parameters return meter.TimeSignature(f'{numerator}/{denominator}') - def getKeySignatureParameters(self) -> tuple[int, str | None]: + def getKeySignatureParameters(self) -> tuple[int, str|None]: # noinspection SpellCheckingInspection ''' Extract key signature parameters, @@ -622,7 +622,7 @@ def getKeySignatureObject(self) -> t.Union[key.Key, else: return ks.asKey(mode) - def getClefObject(self) -> tuple[clef.Clef | None, int | None]: + def getClefObject(self) -> tuple[clef.Clef|None, int|None]: ''' Extract any clef parameters stored in the key metadata token. Assume that a clef definition suggests a transposition. @@ -641,7 +641,7 @@ def getClefObject(self) -> tuple[clef.Clef | None, int | None]: # placing this import in method for now; clef.py may import this module UNLIKELY from music21 import clef - clefObj: clef.Clef | None = None + clefObj: clef.Clef|None = None transposeSemitones = None if '-8va' in self.data.lower(): @@ -654,7 +654,7 @@ def getClefObject(self) -> tuple[clef.Clef | None, int | None]: # if not defined, returns None, None return clefObj, transposeSemitones - def getMetronomeMarkObject(self) -> tempo.MetronomeMark | None: + def getMetronomeMarkObject(self) -> tempo.MetronomeMark|None: ''' Extract any tempo parameters stored in a tempo metadata token. @@ -711,7 +711,7 @@ def getMetronomeMarkObject(self) -> tempo.MetronomeMark | None: # get a symbolic and numerical value if available number: float = -1 # sentinel = None - referent: float | None = None + referent: float|None = None if nonText: if '=' in nonText: durs, numberStr = nonText.split('=') @@ -917,7 +917,7 @@ def isRegular(self) -> bool: else: return False - def isRepeatBracket(self) -> int | t.Literal[False]: + def isRepeatBracket(self) -> int|t.Literal[False]: ''' Return a number if this defines a repeat bracket for an alternate ending otherwise returns False. @@ -936,7 +936,7 @@ def isRepeatBracket(self) -> int | t.Literal[False]: else: return False - def getBarObject(self) -> bar.Barline | None: + def getBarObject(self) -> bar.Barline|None: ''' Return a music21 bar object @@ -947,7 +947,7 @@ def getBarObject(self) -> bar.Barline | None: ''' from music21 import bar - m21bar: bar.Barline | None + m21bar: bar.Barline|None if self.isRepeat(): if self.repeatForm in ('end', 'start'): m21bar = bar.Repeat(direction=self.repeatForm) @@ -990,11 +990,11 @@ def __init__(self, src: str = ''): self.numberNotesNormal: int = 1 # store an m21 tuplet object - self.tupletObj: duration.Tuplet | None = None + self.tupletObj: duration.Tuplet|None = None def updateRatio( self, - timeSignatureObj: meter.TimeSignature | None = None + timeSignatureObj: meter.TimeSignature|None = None ) -> None: # noinspection PyShadowingNames ''' @@ -1078,7 +1078,7 @@ def updateRatio( splitTuplet = self.src.strip().split(':') tupletNumber = splitTuplet[0] - normalNotes: int | None = None + normalNotes: int|None = None if len(splitTuplet) >= 2 and splitTuplet[1] != '': normalNotes = int(splitTuplet[1]) @@ -1181,7 +1181,7 @@ class ABCSlurStart(ABCToken): def __init__(self, src: str = ''): super().__init__(src) - self.slurObj: spanner.Slur | None = None + self.slurObj: spanner.Slur|None = None def fillSlur(self): ''' @@ -1210,7 +1210,7 @@ class ABCCrescStart(ABCToken): def __init__(self, src: str = ''): super().__init__(src) - self.crescObj: dynamics.Crescendo | None = None + self.crescObj: dynamics.Crescendo|None = None def fillCresc(self) -> None: from music21 import dynamics @@ -1226,7 +1226,7 @@ class ABCDimStart(ABCToken): def __init__(self, src: str = ''): super().__init__(src) - self.dimObj: dynamics.Diminuendo | None = None + self.dimObj: dynamics.Diminuendo|None = None def fillDim(self): from music21 import dynamics @@ -1353,40 +1353,40 @@ def __init__(self, src='', carriedAccidental: str = ''): self.chordSymbols: list[str] = [] # context attributes - self.inBar: bool | None = None - self.inBeam: bool | None = None - self.inGrace: bool | None = None + self.inBar: bool|None = None + self.inBeam: bool|None = None + self.inGrace: bool|None = None # provide default duration from handler; may change during piece - self.activeDefaultQuarterLength: float | None = None + self.activeDefaultQuarterLength: float|None = None # store if a broken symbol applies; a pair of symbols, position (left, right) - self.brokenRhythmMarker: tuple[str, str] | None = None + self.brokenRhythmMarker: tuple[str, str]|None = None # store key signature for pitch processing; this is an M21Object - self.activeKeySignature: key.KeySignature | None = None + self.activeKeySignature: key.KeySignature|None = None # store a tuplet if active - self.activeTuplet: duration.Tuplet | None = None + self.activeTuplet: duration.Tuplet|None = None # store a spanner if active self.applicableSpanners: list[spanner.Spanner] = [] # store a tie type if active - self.tie: str | None = None + self.tie: str|None = None # store articulations if active self.articulations: list[str] = [] # set to True if a modification of key signature # set to False if an altered tone part of a Key - self.accidentalDisplayStatus: bool | None = None + self.accidentalDisplayStatus: bool|None = None # determined during parse() based on if pitch chars are present self.isRest: bool = False # Pitch and duration attributes for m21 conversion # they are set via parse() based on other contextual information. - self.pitchName: str | None = None # if None, a rest or chord + self.pitchName: str|None = None # if None, a rest or chord self.quarterLength: float = 0.0 @staticmethod @@ -1420,7 +1420,7 @@ def getPitchName( self, strSrc: str, forceKeySignature=None - ) -> tuple[str | None, bool | None]: + ) -> tuple[str|None, bool|None]: ''' Given a note or rest string without a chord symbol, return a music21 pitch string or None (if a rest), @@ -1536,7 +1536,7 @@ def getPitchName( raise ABCHandlerException('Carried accidentals not rendered moot.') # if there is an explicit accidental, regardless of key, it should # be shown: this will work for naturals well - accidentalDisplayStatus: bool | None + accidentalDisplayStatus: bool|None if carriedAccString: # An accidental carrying through the measure is supposed to be applied. # This will be set iff no explicit accidental is attached to the note. @@ -1581,7 +1581,7 @@ def getPitchName( def getQuarterLength(self, strSrc: str, - forceDefaultQuarterLength: float | None = None) -> float: + forceDefaultQuarterLength: float|None = None) -> float: ''' Called with parse(), after context processing, to calculate duration @@ -1629,7 +1629,7 @@ def getQuarterLength(self, >>> an.getQuarterLength('A', forceDefaultQuarterLength=1.0) 1.875 ''' - activeDefaultQuarterLength: float | None + activeDefaultQuarterLength: float|None if forceDefaultQuarterLength is not None: activeDefaultQuarterLength = forceDefaultQuarterLength else: # may be None @@ -1711,16 +1711,16 @@ def getQuarterLength(self, def parse( self, - forceDefaultQuarterLength: float | None = None, - forceKeySignature: key.KeySignature | None = None + forceDefaultQuarterLength: float|None = None, + forceKeySignature: key.KeySignature|None = None ) -> None: # environLocal.printDebug(['parse', self.src]) self.chordSymbols, nonChordSymStr = self._splitChordSymbols(self.src) # get pitch name form remaining string # rests will have a pitch name of None - pn: str | None - accDisp: bool | None + pn: str|None + accDisp: bool|None try: pn, accDisp = self.getPitchName(nonChordSymStr, forceKeySignature=forceKeySignature) @@ -1864,7 +1864,7 @@ def __init__(self, @staticmethod def _getLinearContext(source: Sequence[_T], - i: int) -> tuple[_T | None, _T, _T | None, _T | None]: + i: int) -> tuple[_T|None, _T, _T|None, _T|None]: ''' Find the local context of a string or iterable of objects beginning at a particular index. @@ -2102,8 +2102,8 @@ def processComment(self): @staticmethod def startsMetadata(c: str, - cNext: str | None, - cNextNext: str | None) -> bool: + cNext: str|None, + cNextNext: str|None) -> bool: ''' Returns True if this context describes the start of a metadata section, like @@ -2559,8 +2559,8 @@ def tokenProcess(self) -> None: lastDefaultQL = None lastKeySignature = None lastTimeSignatureObj = None # an m21 object - lastTupletToken: ABCTuplet | None = None # a token obj; keeps count of usage - lastTieToken: ABCTie | None = None + lastTupletToken: ABCTuplet|None = None # a token obj; keeps count of usage + lastTieToken: ABCTie|None = None lastStaccToken = None lastUpToken = None lastDownToken = None @@ -2812,7 +2812,7 @@ def definesReferenceNumbers(self): return True return False - def splitByReferenceNumber(self) -> dict[int | None, ABCHandler]: + def splitByReferenceNumber(self) -> dict[int|None, ABCHandler]: # noinspection PyShadowingNames r''' Split tokens by reference numbers. @@ -2887,7 +2887,7 @@ def splitByReferenceNumber(self) -> dict[int | None, ABCHandler]: if not self.tokens: raise ABCHandlerException('must process tokens before calling split') - ahDict: dict[int | None, ABCHandler] = {} + ahDict: dict[int|None, ABCHandler] = {} # tokens in this list are prepended to all tunes: prependToAllList = [] @@ -3289,7 +3289,7 @@ def hasNotes(self) -> bool: else: return False - def getTitle(self) -> str | None: + def getTitle(self) -> str|None: ''' Get the first title tag. Used for testing. @@ -3316,8 +3316,8 @@ def __init__(self) -> None: # tokens are ABC objects in a linear stream super().__init__() - self.leftBarToken: ABCBar | None = None - self.rightBarToken: ABCBar | None = None + self.leftBarToken: ABCBar|None = None + self.rightBarToken: ABCBar|None = None def __add__(self, other): ah = self.__class__() # will get the same class type @@ -3402,10 +3402,10 @@ class ABCFile(prebase.ProtoM21Object): ''' def __init__(self, abcVersion: tuple[int, int, int] = defaults.abcVersionDefault): self.abcVersion: tuple[int, int, int] = abcVersion - self.file: t.IO | None = None - self.filename: str | pathlib.Path = '' + self.file: t.IO|None = None + self.filename: str|pathlib.Path = '' - def open(self, filename: str | pathlib.Path): + def open(self, filename: str|pathlib.Path): ''' Open a file for reading ''' @@ -3508,7 +3508,7 @@ def extractReferenceNumber(strSrc: str, number: int) -> str: referenceNumbers = '\n'.join(collect) return referenceNumbers - def readstr(self, strSrc: str, number: int | None = None) -> ABCHandler: + def readstr(self, strSrc: str, number: int|None = None) -> ABCHandler: ''' Read a string and process all Tokens. Returns a ABCHandler instance. diff --git a/music21/abcFormat/translate.py b/music21/abcFormat/translate.py index 3db7e2ad23..2dd07a439d 100644 --- a/music21/abcFormat/translate.py +++ b/music21/abcFormat/translate.py @@ -59,8 +59,8 @@ def abcToStreamPart( abcHandler: abcFormat.ABCHandler, - inputM21: stream.Part | None = None, - spannerBundle: spanner.SpannerBundle | None = None + inputM21: stream.Part|None = None, + spannerBundle: spanner.SpannerBundle|None = None ) -> stream.Part: ''' Handler conversion of a single Part of a Score with multiple Parts. @@ -82,7 +82,7 @@ def abcToStreamPart( clefSet = None postTransposition = 0 - dst: stream.Part | stream.Measure + dst: stream.Part|stream.Measure mergedHandlers: list[abcFormat.ABCHandler] = [] @@ -253,7 +253,7 @@ def abcToStreamPart( def parseTokens( mh: abcFormat.ABCHandler, - dst: stream.Measure | stream.Part, + dst: stream.Measure|stream.Part, p: stream.Part, useMeasures: bool ) -> tuple[int, bool]: @@ -289,7 +289,7 @@ def parseTokens( def parseABCNote( t: abcFormat.ABCNote, - dst: stream.Measure | stream.Part, + dst: stream.Measure|stream.Part, ) -> None: ''' Parse an ABCNote object and add it to the destination stream. @@ -297,7 +297,7 @@ def parseABCNote( from music21 import abcFormat n: note.GeneralNote - cs: harmony.ChordSymbol | harmony.NoChord + cs: harmony.ChordSymbol|harmony.NoChord # add the attached chord symbol if t.chordSymbols: @@ -394,7 +394,7 @@ def parseABCNote( def metadataToM21Object( t: abcFormat.ABCMetadata, - dst: stream.Measure | stream.Part, + dst: stream.Measure|stream.Part, postTransposition: int, clefSet: bool, useMeasures: bool, diff --git a/music21/alpha/analysis/fixer.py b/music21/alpha/analysis/fixer.py index 156b5d4aa3..d13e7663a9 100644 --- a/music21/alpha/analysis/fixer.py +++ b/music21/alpha/analysis/fixer.py @@ -376,7 +376,7 @@ def __init__(self, changes, midiStream, omrStream, recognizers, markChangeColor= self.recognizers = recognizers self.markChangeColor = markChangeColor - def findOrnament(self, busyNotes, simpleNotes) -> expressions.Ornament | None: + def findOrnament(self, busyNotes, simpleNotes) -> expressions.Ornament|None: ''' Finds an ornament in busyNotes based from simpleNote using provided recognizers. @@ -415,7 +415,7 @@ def addOrnament(self, return True return False - def fix(self, *, show=False, inPlace=True) -> OMRMidiFixer | None: + def fix(self, *, show=False, inPlace=True) -> OMRMidiFixer|None: ''' Corrects missed ornaments in omrStream according to midiStream :param show: Whether to show results @@ -423,7 +423,7 @@ def fix(self, *, show=False, inPlace=True) -> OMRMidiFixer | None: return a new OrnamentFixer with changes ''' changes = self.changes - sa: aligner.StreamAligner | None = None + sa: aligner.StreamAligner|None = None omrNotesLabeledOrnament = [] midiNotesAlreadyFixedForOrnament = [] diff --git a/music21/alpha/analysis/ornamentRecognizer.py b/music21/alpha/analysis/ornamentRecognizer.py index 40ed0190d2..51a5e215a3 100644 --- a/music21/alpha/analysis/ornamentRecognizer.py +++ b/music21/alpha/analysis/ornamentRecognizer.py @@ -48,7 +48,7 @@ def calculateOrnamentNoteQl( def calculateOrnamentTotalQl( self, busyNotes: list[note.GeneralNote], - simpleNotes: list[note.GeneralNote] | None = None + simpleNotes: list[note.GeneralNote]|None = None ) -> OffsetQL: ''' Returns total length of trill assuming busy notes are all an expanded trill. @@ -77,7 +77,7 @@ def __init__(self, checkNachschlag=False): self.acceptableInterval = 3 self.minimumLengthForNachschlag = 5 - def recognize(self, busyNotes, simpleNotes=None) -> bool | expressions.Trill: + def recognize(self, busyNotes, simpleNotes=None) -> bool|expressions.Trill: ''' Tries to identify the busy notes as a trill. @@ -193,7 +193,7 @@ def recognize( self, busyNotes, simpleNotes=None, - ) -> bool | expressions.Turn | expressions.InvertedTurn: + ) -> bool|expressions.Turn|expressions.InvertedTurn: ''' Tries to identify the busy notes as a turn or inverted turn. diff --git a/music21/analysis/discrete.py b/music21/analysis/discrete.py index e8cd6a99aa..d32f50f182 100644 --- a/music21/analysis/discrete.py +++ b/music21/analysis/discrete.py @@ -79,7 +79,7 @@ def __init__(self, referenceStream=None): # store alternative solutions, which may be sorted or not self.alternativeSolutions = [] - def _rgbToHex(self, rgb: Sequence[float | int]) -> str: + def _rgbToHex(self, rgb: Sequence[float|int]) -> str: ''' Utility conversion method @@ -389,7 +389,7 @@ def _convoluteDistribution(self, pcDistribution, weightType='major'): solution[i] += (toneWeights[(j - i) % 12] * pcDistribution[j]) return solution - def _getLikelyKeys(self, keyResults, differences) -> list[t.Any] | None: + def _getLikelyKeys(self, keyResults, differences) -> list[t.Any]|None: ''' Takes in a list of probable key results in points and returns a list of keys in letters, sorted from most likely to least likely. ''' @@ -407,7 +407,7 @@ def _getLikelyKeys(self, keyResults, differences) -> list[t.Any] | None: # environLocal.printDebug(['added likely key', likelyKeys[pc]]) return likelyKeys - def _getDifference(self, keyResults, pcDistribution, weightType) -> None | list[int | float]: + def _getDifference(self, keyResults, pcDistribution, weightType) -> None|list[int|float]: ''' Takes in a list of numerical probable key results and returns the difference of the top two keys. @@ -416,7 +416,7 @@ def _getDifference(self, keyResults, pcDistribution, weightType) -> None | list[ if keyResults is None: return None - solution: list[int | float] = [0.0] * 12 + solution: list[int|float] = [0.0] * 12 top = [0.0] * 12 bottomRight = [0.0] * 12 bottomLeft = [0.0] * 12 @@ -951,12 +951,12 @@ class Ambitus(DiscreteAnalysis): # provide possible string matches for this processor identifiers = ['ambitus', 'span'] - def __init__(self, referenceStream: stream.Stream | None = None): + def __init__(self, referenceStream: stream.Stream|None = None): super().__init__(referenceStream=referenceStream) # Store the min and max Pitch instances for referenceStream # set by getPitchSpan(), which is called by _generateColors() - self.minPitchObj: pitch.Pitch | None = None - self.maxPitchObj: pitch.Pitch | None = None + self.minPitchObj: pitch.Pitch|None = None + self.maxPitchObj: pitch.Pitch|None = None self._pitchSpanColors: OrderedDict[int, str] = OrderedDict() self._generateColors() @@ -1004,7 +1004,7 @@ def _generateColors(self, numColors=None): # environLocal.printDebug([self._pitchSpanColors]) - def getPitchSpan(self, subStream) -> tuple[pitch.Pitch, pitch.Pitch] | None: + def getPitchSpan(self, subStream) -> tuple[pitch.Pitch, pitch.Pitch]|None: ''' For a given subStream, return a tuple consisting of the two pitches with the minimum and maximum pitch space value. @@ -1337,7 +1337,7 @@ def analyzeStream( # this synonym is being added for compatibility method = 'span' - analysisClassName: type[DiscreteAnalysis] | None = analysisClassFromMethodName(method) + analysisClassName: type[DiscreteAnalysis]|None = analysisClassFromMethodName(method) if analysisClassName is not None: obj = analysisClassName() @@ -1349,7 +1349,7 @@ def analyzeStream( # noinspection SpellCheckingInspection -def analysisClassFromMethodName(method: str) -> type[DiscreteAnalysis] | None: +def analysisClassFromMethodName(method: str) -> type[DiscreteAnalysis]|None: ''' Returns an analysis class given a method name, or None if none can be found @@ -1378,7 +1378,7 @@ def analysisClassFromMethodName(method: str) -> type[DiscreteAnalysis] | None: BellmanBudge, TemperleyKostkaPayne, ] - match: type[DiscreteAnalysis] | None = None + match: type[DiscreteAnalysis]|None = None for analysisClass in analysisClasses: # this is a very loose matching, as there are few classes now if (method.lower() in analysisClass.__name__.lower() diff --git a/music21/analysis/harmonicFunction.py b/music21/analysis/harmonicFunction.py index 1519c85038..4037267bc1 100644 --- a/music21/analysis/harmonicFunction.py +++ b/music21/analysis/harmonicFunction.py @@ -102,8 +102,8 @@ class HarmonicFunction(common.enums.StrEnum): def functionToRoman(thisHarmonicFunction: HarmonicFunction, - keyOrScale: key.Key | scale.ConcreteScale | str = 'C' - ) -> roman.RomanNumeral | None: + keyOrScale: key.Key|scale.ConcreteScale|str = 'C' + ) -> roman.RomanNumeral|None: ''' Takes harmonic function labels (such as 'T' for major tonic) with a key (keyOrScale, default = 'C') and @@ -197,7 +197,7 @@ def functionToRoman(thisHarmonicFunction: HarmonicFunction, def romanToFunction(rn: roman.RomanNumeral, onlyHauptHarmonicFunction: bool = False - ) -> HarmonicFunction | None: + ) -> HarmonicFunction|None: ''' Takes a Roman numeral and returns a corresponding harmonic function label. diff --git a/music21/analysis/reduction.py b/music21/analysis/reduction.py index fa7551973c..5847a74677 100644 --- a/music21/analysis/reduction.py +++ b/music21/analysis/reduction.py @@ -468,7 +468,7 @@ class PartReduction: def __init__(self, srcScore=None, *, - partGroups: list[dict[str, t.Any]] | None = None, + partGroups: list[dict[str, t.Any]]|None = None, fillByMeasure: bool = True, segmentByTarget: bool = True, normalize: bool = True, @@ -484,7 +484,7 @@ def __init__(self, # TODO: typed dict self._partBundles: list[dict[str, t.Any]] = [] # a dictionary of part id to a list of events - self._eventSpans: dict[str | int, list[t.Any]] = {} + self._eventSpans: dict[str|int, list[t.Any]] = {} # define how parts are grouped # a list of dictionaries, with keys for name, color, and a match list diff --git a/music21/analysis/windowed.py b/music21/analysis/windowed.py index 48ac7df91e..58236939bf 100644 --- a/music21/analysis/windowed.py +++ b/music21/analysis/windowed.py @@ -244,9 +244,9 @@ def analyze(self, windowSize, windowType='overlap'): def process(self, - minWindow: int | None = 1, - maxWindow: int | None = 1, - windowStepSize: int | str = 1, + minWindow: int|None = 1, + maxWindow: int|None = 1, + windowStepSize: int|str = 1, windowType='overlap', includeTotalWindow=True): # noinspection PyShadowingNames diff --git a/music21/articulations.py b/music21/articulations.py index fdb00874dd..d9d1485790 100644 --- a/music21/articulations.py +++ b/music21/articulations.py @@ -148,7 +148,7 @@ def __init__(self, **keywords) -> None: self._volumeShift: float = 0.0 self.lengthShift: float = 1.0 self.tieAttach: str = 'first' # attach to first or last or all notes after split - self.displayText: str | None = None + self.displayText: str|None = None def _reprInternal(self): return '' @@ -582,7 +582,7 @@ class PullOff(spanner.Spanner, TechnicalIndication): pass class FretBend(FretIndication): - bendAlter: interval.IntervalBase | None = None + bendAlter: interval.IntervalBase|None = None preBend: t.Any = None release: t.Any = None withBar: t.Any = None diff --git a/music21/audioSearch/__init__.py b/music21/audioSearch/__init__.py index 015e2bb8c3..ba358fd62e 100644 --- a/music21/audioSearch/__init__.py +++ b/music21/audioSearch/__init__.py @@ -525,11 +525,11 @@ def detectPitchFrequencies(freqFromAQList, useScale=None): def smoothFrequencies( - frequencyList: list[int | float], + frequencyList: list[int|float], *, smoothLevels=7, inPlace=False -) -> list[int] | None: +) -> list[int]|None: ''' Smooths the shape of the signal in order to avoid false detections in the fundamental frequency. Takes in a list of ints or floats. diff --git a/music21/bar.py b/music21/bar.py index 3b0eba6f03..2e73ed6cdc 100644 --- a/music21/bar.py +++ b/music21/bar.py @@ -266,7 +266,7 @@ class Repeat(repeat.RepeatMark, Barline): {4.0} ''' # _repeatDots = None # not sure what this is for; inherited from old modules - def __init__(self, direction: str = 'start', times: int | None = None, **keywords): + def __init__(self, direction: str = 'start', times: int|None = None, **keywords): repeat.RepeatMark.__init__(self) if direction == 'start': barType = 'heavy-light' @@ -274,8 +274,8 @@ def __init__(self, direction: str = 'start', times: int | None = None, **keyword barType = 'final' Barline.__init__(self, type=barType, **keywords) - self._direction: str | None = None # either start or end - self._times: int | None = None # if an end, how many repeats + self._direction: str|None = None # either start or end + self._times: int|None = None # if an end, how many repeats # start is forward, end is backward in musicxml self.direction = direction # start, end @@ -311,7 +311,7 @@ def direction(self, value: str): raise BarException(f'cannot set repeat direction to: {value}') @property - def times(self) -> int | None: + def times(self) -> int|None: ''' Get or set the "times" property of this barline. This defines how many times the repeat happens. A standard repeat diff --git a/music21/base.py b/music21/base.py index e1a01c3fb7..ccca277de9 100644 --- a/music21/base.py +++ b/music21/base.py @@ -409,7 +409,7 @@ class Music21Object(prebase.ProtoM21Object): True ''' - classSortOrder: int | float = 20 # default classSortOrder + classSortOrder: int|float = 20 # default classSortOrder # these values permit fast class comparisons for performance critical cases isStream = False @@ -465,37 +465,37 @@ class Music21Object(prebase.ProtoM21Object): } def __init__(self, - id: str | int | None = None, # pylint: disable=redefined-builtin - groups: Groups | None = None, - sites: Sites | None = None, - duration: Duration | None = None, - activeSite: stream.Stream | None = None, - style: Style | None = None, - editorial: Editorial | None = None, + id: str|int|None = None, # pylint: disable=redefined-builtin + groups: Groups|None = None, + sites: Sites|None = None, + duration: Duration|None = None, + activeSite: stream.Stream|None = None, + style: Style|None = None, + editorial: Editorial|None = None, offset: OffsetQL = 0.0, - quarterLength: OffsetQLIn | None = None, + quarterLength: OffsetQLIn|None = None, **keywords): # do not call super().__init__() since it just wastes time - self._id: str | int | None = id + self._id: str|int|None = id # None is stored as the internal location of an obj w/o any sites - self._activeSite: stream.Stream | weakref.ReferenceType | None = None + self._activeSite: stream.Stream|weakref.ReferenceType|None = None # offset when no activeSite is available self._naiveOffset: OffsetQL = offset # offset when activeSite is already garbage collected/dead, # as in short-lived sites # like .getElementsByClass().stream() - self._activeSiteStoredOffset: float | fractions.Fraction | None = None + self._activeSiteStoredOffset: float|fractions.Fraction|None = None # store a derivation object to track derivations from other Streams # pass a reference to this object - self._derivation: Derivation | None = None + self._derivation: Derivation|None = None - self._style: Style | None = style - self._editorial: Editorial | None = None + self._style: Style|None = style + self._editorial: Editorial|None = None # private duration storage; managed by property - self._duration: Duration | None = duration + self._duration: Duration|None = duration if duration is not None: duration.client = self self._priority = 0 # default is zero @@ -534,7 +534,7 @@ def __hash__(self) -> int: return id(self) >> 4 @property - def id(self) -> int | str: + def id(self) -> int|str: ''' A unique identification string or int; not to be confused with Python's built-in `id()` method. However, if not set, will return @@ -550,7 +550,7 @@ def id(self) -> int | str: return builtins.id(self) @id.setter - def id(self, new_id: int | str): + def id(self, new_id: int|str): if isinstance(new_id, int) and new_id > defaults.minIdNumberToConsiderMemoryLocation: msg = 'Setting an ID that could be mistaken for a memory location ' msg += f'is discouraged: got {new_id}' @@ -578,9 +578,9 @@ def mergeAttributes(self, other: Music21Object) -> None: self.groups = copy.deepcopy(other.groups) def _deepcopySubclassable(self: _M21T, - memo: dict[int, t.Any] | None = None, + memo: dict[int, t.Any]|None = None, *, - ignoreAttributes: set[str] | None = None) -> _M21T: + ignoreAttributes: set[str]|None = None) -> _M21T: ''' Subclassable __deepcopy__ helper so that the same attributes do not need to be called for each Music21Object subclass. @@ -622,7 +622,7 @@ def _deepcopySubclassable(self: _M21T, return new - def __deepcopy__(self: _M21T, memo: dict[int, t.Any] | None = None) -> _M21T: + def __deepcopy__(self: _M21T, memo: dict[int, t.Any]|None = None) -> _M21T: ''' Helper method to copy.py's deepcopy function. Call it from there. @@ -800,7 +800,7 @@ def style(self) -> Style: return self._style @style.setter - def style(self, newStyle: Style | None): + def style(self, newStyle: Style|None): self._style = newStyle # convenience. @@ -857,7 +857,7 @@ def derivation(self) -> Derivation: return self._derivation @derivation.setter - def derivation(self, newDerivation: Derivation | None) -> None: + def derivation(self, newDerivation: Derivation|None) -> None: self._derivation = newDerivation def clearCache(self, **keywords) -> None: @@ -885,7 +885,7 @@ def clearCache(self, **keywords) -> None: @overload def getOffsetBySite( self, - site: stream.Stream | None, + site: stream.Stream|None, *, returnSpecial: t.Literal[False] = False, ) -> OffsetQL: @@ -894,19 +894,19 @@ def getOffsetBySite( @overload def getOffsetBySite( self, - site: stream.Stream | None, + site: stream.Stream|None, *, returnSpecial: bool = False, - ) -> OffsetQL | OffsetSpecial: + ) -> OffsetQL|OffsetSpecial: return 0.0 # dummy until Astroid #1015 is fixed. Replace with ... # using bool instead of t.Literal[True] because of def getOffsetBySite( self, - site: stream.Stream | None, + site: stream.Stream|None, *, returnSpecial: bool = False, - ) -> OffsetQL | OffsetSpecial: + ) -> OffsetQL|OffsetSpecial: ''' If this class has been registered in a container such as a Stream, that container can be provided here, and the offset in that object @@ -1022,7 +1022,7 @@ def getOffsetBySite( ) from se def setOffsetBySite(self, - site: stream.Stream | None, + site: stream.Stream|None, value: OffsetQLIn): ''' Change the offset for a site. These are equivalent: @@ -1076,7 +1076,7 @@ def setOffsetBySite(self, def getOffsetInHierarchy( self, - site: stream.Stream | None + site: stream.Stream|None ) -> OffsetQL: ''' For an element which may not be in site, but might be in a Stream in site (or further @@ -1148,7 +1148,7 @@ def getOffsetInHierarchy( raise SitesException(f'Element {self} is not in hierarchy of {site}') def getSpannerSites(self, - spannerClassList: Iterable | None = None + spannerClassList: Iterable|None = None ) -> list[spanner.Spanner]: ''' Return a list of all :class:`~music21.spanner.Spanner` objects @@ -1290,30 +1290,30 @@ def getContextByClass( sortByCreationTime=False, followDerivation=True, priorityTargetOnly=False, - ) -> _M21T | None: + ) -> _M21T|None: return None # until Astroid #1015 @overload def getContextByClass( self, - className: str | None, + className: str|None, *, getElementMethod=ElementSearch.AT_OR_BEFORE, sortByCreationTime=False, followDerivation=True, priorityTargetOnly=False, - ) -> Music21Object | None: + ) -> Music21Object|None: return None # until Astroid #1015 def getContextByClass( self, - className: type[_M21T] | str | None, + className: type[_M21T]|str|None, *, getElementMethod: ElementSearch = ElementSearch.AT_OR_BEFORE, sortByCreationTime=False, followDerivation=True, priorityTargetOnly=False, - ) -> _M21T | Music21Object | None: + ) -> _M21T|Music21Object|None: # noinspection PyShadowingNames ''' A very powerful method in music21 of fundamental importance: Returns @@ -1783,7 +1783,7 @@ def contextSites( callerFirst=None, memo=None, offsetAppend: OffsetQL = 0.0, - sortByCreationTime: t.Literal['reverse'] | bool = False, + sortByCreationTime: t.Literal['reverse']|bool = False, priorityTarget=None, followDerivation=True, priorityTargetOnly=False, @@ -1797,7 +1797,7 @@ def contextSites( callerFirst=None, memo=None, offsetAppend: OffsetQL = 0.0, - sortByCreationTime: t.Literal['reverse'] | bool = False, + sortByCreationTime: t.Literal['reverse']|bool = False, priorityTarget=None, returnSortTuples: t.Literal[False] = False, followDerivation=True, @@ -1812,12 +1812,12 @@ def contextSites( callerFirst=None, memo=None, offsetAppend: OffsetQL = 0.0, - sortByCreationTime: t.Literal['reverse'] | bool = False, + sortByCreationTime: t.Literal['reverse']|bool = False, priorityTarget=None, returnSortTuples: bool = False, followDerivation=True, priorityTargetOnly=False, - ) -> Generator[ContextTuple | ContextSortTuple, None, None]: + ) -> Generator[ContextTuple|ContextSortTuple, None, None]: ''' A generator that returns a list of namedtuples of sites to search for a context... @@ -2163,7 +2163,7 @@ def getAllContextsByClass(self, className): # ------------------------------------------------------------------------- def next(self, - className: type[Music21Object] | str | None = None, + className: type[Music21Object]|str|None = None, *, activeSiteOnly=False): ''' @@ -2283,7 +2283,7 @@ def next(self, raise Music21Exception('Maximum recursion!') def previous(self, - className: type[Music21Object] | str | None = None, + className: type[Music21Object]|str|None = None, *, activeSiteOnly=False): ''' @@ -2391,7 +2391,7 @@ def _getActiveSite(self): else: # pragma: no cover return self._activeSite - def _setActiveSite(self, site: stream.Stream | None): + def _setActiveSite(self, site: stream.Stream|None): # environLocal.printDebug(['_setActiveSite() called:', 'self', self, 'site', site]) # NOTE: this is a performance intensive call @@ -2590,7 +2590,7 @@ def offset(self, value: OffsetQLIn): self._naiveOffset = offset def sortTuple(self, - useSite: t.Literal[False] | stream.Stream | None = False, + useSite: t.Literal[False]|stream.Stream|None = False, raiseExceptionOnMiss: bool = False ) -> SortTuple: ''' @@ -2696,13 +2696,13 @@ def sortTuple(self, music21.sites.SitesException: an entry for this object 0x... is not stored in stream ''' - useSiteNoFalse: stream.Stream | None + useSiteNoFalse: stream.Stream|None if useSite is False: # False or a Site; since None is a valid site, default is False useSiteNoFalse = self.activeSite else: useSiteNoFalse = useSite - foundOffset: OffsetQL | OffsetSpecial + foundOffset: OffsetQL|OffsetSpecial if useSiteNoFalse is None: foundOffset = self.offset else: @@ -2840,8 +2840,8 @@ def _setPriority(self, value): def write( self, - fmt: str | None = None, - fp: str | pathlib.Path | IOBase | None = None, + fmt: str|None = None, + fp: str|pathlib.Path|IOBase|None = None, **keywords ) -> pathlib.Path: # pragma: no cover ''' @@ -3312,7 +3312,7 @@ def splitAtQuarterLength( def splitByQuarterLengths( self, - quarterLengthList: list[int | float | fractions.Fraction], + quarterLengthList: list[int|float|fractions.Fraction], addTies=True, displayTiedAccidentals=False ) -> _SplitTuple: @@ -3479,7 +3479,7 @@ def splitAtDurations(self) -> _SplitTuple: # temporal and beat based positioning @property - def measureNumber(self) -> int | None: + def measureNumber(self) -> int|None: # noinspection PyShadowingNames ''' Return the measure number of a :class:`~music21.stream.Measure` that contains this @@ -3552,7 +3552,7 @@ def measureNumber(self) -> int | None: mNumber = m.number # type: ignore return mNumber - def _getMeasureOffset(self, includeMeasurePadding=True) -> float | fractions.Fraction: + def _getMeasureOffset(self, includeMeasurePadding=True) -> float|fractions.Fraction: # noinspection PyShadowingNames ''' Try to obtain the nearest Measure that contains this object, @@ -3620,7 +3620,7 @@ def _getTimeSignatureForBeat(self) -> meter.TimeSignature: extracted to make sure that all three of the routines use the same one. ''' from music21 import meter - ts: meter.TimeSignature | None = self.getContextByClass( + ts: meter.TimeSignature|None = self.getContextByClass( meter.TimeSignature, getElementMethod=ElementSearch.AT_OR_BEFORE_OFFSET ) @@ -3629,7 +3629,7 @@ def _getTimeSignatureForBeat(self) -> meter.TimeSignature: return ts @property - def beat(self) -> fractions.Fraction | float: + def beat(self) -> fractions.Fraction|float: # noinspection PyShadowingNames ''' Return the beat of this object as found in the most @@ -3933,7 +3933,7 @@ def _getSeconds(self) -> float: # once we have mm, simply pass in this duration return mm.durationToSeconds(self.duration) - def _setSeconds(self, value: int | float) -> None: + def _setSeconds(self, value: int|float) -> None: from music21 import tempo ti = self.getContextByClass(tempo.TempoIndication) if ti is None: diff --git a/music21/beam.py b/music21/beam.py index c5da526cad..7a86facfd0 100644 --- a/music21/beam.py +++ b/music21/beam.py @@ -272,7 +272,7 @@ def naiveBeams(srcList: Iterable[base.Music21Object]): 2/None>/>, None] ''' - beamsList: list[Beams | None] = [] + beamsList: list[Beams|None] = [] for el in srcList: # if a dur cannot be beamable under any circumstance, replace # it with None; this includes Rests @@ -291,7 +291,7 @@ def naiveBeams(srcList: Iterable[base.Music21Object]): return beamsList @staticmethod - def removeSandwichedUnbeamables(beamsList: list[Beams | None]): + def removeSandwichedUnbeamables(beamsList: list[Beams|None]): # noinspection PyShadowingNames ''' Go through the naiveBeamsList and remove beams from objects surrounded @@ -410,7 +410,7 @@ def mergeConnectingPartialBeams(beamsList): return beamsList @staticmethod - def sanitizePartialBeams(beamsList: list[Beams | None]) -> list[Beams | None]: + def sanitizePartialBeams(beamsList: list[Beams|None]) -> list[Beams|None]: ''' It is possible at a late stage to have beams that only consist of partials or beams with a 'start' followed by 'partial/left' or possibly 'stop' followed diff --git a/music21/braille/segment.py b/music21/braille/segment.py index 9d262d96e1..052dcf2560 100644 --- a/music21/braille/segment.py +++ b/music21/braille/segment.py @@ -120,8 +120,8 @@ class Affinity(enum.IntEnum): ] class GroupingGlobals(t.TypedDict): - keySignature: key.KeySignature | None - timeSignature: meter.TimeSignature | None + keySignature: key.KeySignature|None + timeSignature: meter.TimeSignature|None GROUPING_GLOBALS: GroupingGlobals = { @@ -361,9 +361,9 @@ def __init__(self, lineLength: int = 40): self._groupingDict: dict[SegmentKey, BrailleElementGrouping] = {} self.groupingKeysToProcess: deque[SegmentKey] = deque() - self.currentGroupingKey: SegmentKey | None = None - self.previousGroupingKey: SegmentKey | None = None - self.lastNote: note.Note | None = None + self.currentGroupingKey: SegmentKey|None = None + self.previousGroupingKey: SegmentKey|None = None + self.lastNote: note.Note|None = None self.showClefSigns: bool = False self.upperFirstInNoteFingering: bool = True @@ -597,7 +597,7 @@ def extractInaccordGrouping(self) -> None: if self.currentGroupingKey is None: raise ValueError('currentGroupingKey must not be None to call extractInaccordGrouping') inaccords = self._groupingDict[self.currentGroupingKey] - last_clef: clef.Clef | None = None + last_clef: clef.Clef|None = None seen_voice: bool = False for music21VoiceOrClef in inaccords: if isinstance(music21VoiceOrClef, clef.Clef): @@ -1098,8 +1098,8 @@ class BrailleGrandSegment(BrailleSegment, text.BrailleKeyboard): def __init__(self, lineLength: int = 40): BrailleSegment.__init__(self, lineLength=lineLength) text.BrailleKeyboard.__init__(self, lineLength=lineLength) - self.allKeyPairs: deque[tuple[SegmentKey | None, - SegmentKey | None]] = deque() + self.allKeyPairs: deque[tuple[SegmentKey|None, + SegmentKey|None]] = deque() self.previousGroupingPair = None self.currentGroupingPair = None @@ -1409,7 +1409,7 @@ def findSegments(music21Part, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -1585,7 +1585,7 @@ def prepareSlurredNotes(music21Part, *, slurLongPhraseWithBrackets=True, showShortSlursAndTiesTogether=False, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, ): ''' Takes in a :class:`~music21.stream.Part` and three keywords: @@ -1987,7 +1987,7 @@ def getRawSegments(music21Part, def extractBrailleElements( - music21MeasureOrVoice: stream.Measure | stream.Voice + music21MeasureOrVoice: stream.Measure|stream.Voice ) -> BrailleElementGrouping: ''' Takes in a :class:`~music21.stream.Measure` or :class:`~music21.stream.Voice` @@ -2032,7 +2032,7 @@ def extractBrailleElements( ''' allElements = BrailleElementGrouping() - last_clef: clef.Clef | None = None + last_clef: clef.Clef|None = None for music21Object in music21MeasureOrVoice: # Hold the clef in memory in case the next object is a voice if isinstance(music21Object, clef.Clef): diff --git a/music21/braille/translate.py b/music21/braille/translate.py index 1eb8d004d2..be3d9f71d7 100644 --- a/music21/braille/translate.py +++ b/music21/braille/translate.py @@ -118,7 +118,7 @@ def objectToBraille(music21Obj: base.Music21Object, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -221,7 +221,7 @@ def objectToBraille(music21Obj: base.Music21Object, upperFirstInNoteFingering=upperFirstInNoteFingering, ) -def streamToBraille(music21Stream: stream.Measure | stream.Part | stream.Score | stream.Opus, +def streamToBraille(music21Stream: stream.Measure|stream.Part|stream.Score|stream.Opus, *, inPlace=False, debug=False, @@ -234,7 +234,7 @@ def streamToBraille(music21Stream: stream.Measure | stream.Part | stream.Score | showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -369,7 +369,7 @@ def scoreToBraille(music21Score, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -382,7 +382,7 @@ def scoreToBraille(music21Score, for music21Metadata in music21Score.getElementsByClass(metadata.Metadata): allBrailleLines.append(metadataToString(music21Metadata, returnBrailleUnicode=not debug)) - unprocessed_partStaff: stream.PartStaff | None = None + unprocessed_partStaff: stream.PartStaff|None = None def process_unmatched_part_staff_as_single_part(): nonlocal unprocessed_partStaff @@ -505,7 +505,7 @@ def metadataToString(music21Metadata: metadata.Metadata, returnBrailleUnicode=Fa # we don't put software versions in braille output continue - namespaceName: str | None = music21Metadata.uniqueNameToNamespaceName(uniqueName) + namespaceName: str|None = music21Metadata.uniqueNameToNamespaceName(uniqueName) if not namespaceName: # we don't put custom metadata in braille output continue @@ -538,7 +538,7 @@ def opusToBraille(music21Opus, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -585,7 +585,7 @@ def measureToBraille(music21Measure, showFirstMeasureNumber=False, # observe False! showHand=None, showHeading=False, # observe False! - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -647,7 +647,7 @@ def partToBraille(music21Part, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, @@ -707,7 +707,7 @@ def keyboardPartsToBraille(keyboardScore, showFirstMeasureNumber=True, showHand=None, showHeading=True, - showLongSlursAndTiesTogether: bool | None = None, + showLongSlursAndTiesTogether: bool|None = None, showShortSlursAndTiesTogether=False, slurLongPhraseWithBrackets=True, suppressOctaveMarks=False, diff --git a/music21/capella/fromCapellaXML.py b/music21/capella/fromCapellaXML.py index e1b28eed8b..11b5b52c16 100644 --- a/music21/capella/fromCapellaXML.py +++ b/music21/capella/fromCapellaXML.py @@ -175,7 +175,7 @@ def partScoreFromSystemScore(self, systemScore: stream.Score) -> stream.Score: # this line is redundant currently, since all we have in systemScore # are Systems, but later there will be other things. systemStream = systemScore.getElementsByClass(layout.System) - partDictById: dict[str | int, dict[str, t.Any]] = {} + partDictById: dict[str|int, dict[str, t.Any]] = {} for thisSystem in systemStream: # this line is redundant currently, since all we have in # thisSystem are Parts, but later there will be other things. @@ -193,7 +193,7 @@ def partScoreFromSystemScore(self, systemScore: stream.Score) -> stream.Score: newPart.coreElementsChanged() newScore = stream.Score() # ORDERED DICT - parts: list[stream.Part | None] = [None for i in range(len(partDictById))] + parts: list[stream.Part|None] = [None for i in range(len(partDictById))] for partId in partDictById: partDict = partDictById[partId] parts[partDict['number']] = partDict['part'] diff --git a/music21/chord/__init__.py b/music21/chord/__init__.py index 89736fe429..7a203bba89 100644 --- a/music21/chord/__init__.py +++ b/music21/chord/__init__.py @@ -202,7 +202,7 @@ def __len__(self): def _add_core_or_init(self, notes, *, - useDuration: None | t.Literal[False] | Duration = None): + useDuration: None|t.Literal[False]|Duration = None): ''' This is the private append method called by .add and called by __init__. @@ -393,7 +393,7 @@ def notes(self) -> tuple[note.NotRest, ...]: return tuple(self._notes) @property - def tie(self) -> tie.Tie | None: + def tie(self) -> tie.Tie|None: ''' Get or set a single tie based on all the ties in this Chord. @@ -417,7 +417,7 @@ def tie(self) -> tie.Tie | None: return None @tie.setter - def tie(self, value: tie.Tie | None): + def tie(self, value: tie.Tie|None): for d in self._notes: d.tie = value # set the same instance for each pitch @@ -476,7 +476,7 @@ def volume(self) -> 'music21.volume.Volume': # do NOT change to volume.Volume @volume.setter - def volume(self, expr: None | 'music21.volume.Volume' | int | float): + def volume(self, expr: None|'music21.volume.Volume'|int|float): # Do NOT change typing to volume.Volume because it will take the property as # its name if isinstance(expr, volume.Volume): @@ -545,7 +545,7 @@ def hasComponentVolumes(self) -> bool: # -------------------------------------------------------------------------- # volume per pitch ?? # -------------------------------------------------------------------------- - def setVolumes(self, volumes: Sequence['music21.volume.Volume' | int | float]): + def setVolumes(self, volumes: Sequence['music21.volume.Volume'|int|float]): # do not change typing to volume.Volume -- will get the property of same name. # noinspection PyShadowingNames ''' @@ -783,7 +783,7 @@ def __eq__(self, other): def __hash__(self): return super().__hash__() - def __getitem__(self, key: int | str | note.Note | pitch.Pitch): + def __getitem__(self, key: int|str|note.Note|pitch.Pitch): ''' Get item makes accessing pitch components for the Chord easier @@ -997,7 +997,7 @@ def formatVectorString(vectorList) -> str: return ''.join(msg) # PRIVATE METHODS # - def _findBass(self) -> pitch.Pitch | None: + def _findBass(self) -> pitch.Pitch|None: ''' Returns the lowest Pitch in the chord. @@ -1023,7 +1023,7 @@ def _removePitchByRedundantAttribute( attribute: str, *, inPlace=False - ) -> _ChordType | list[pitch.Pitch]: + ) -> _ChordType|list[pitch.Pitch]: ''' Common method for stripping pitches based on redundancy of one pitch attribute. The `attribute` is provided by a string. @@ -1156,7 +1156,7 @@ def annotateIntervals( stripSpecifiers: bool = True, sortPitches: bool = True, returnList: bool = False - ) -> _ChordType | None | list[str]: + ) -> _ChordType|None|list[str]: # noinspection PyShadowingNames ''' Add lyrics to the chord that show the distance of each note from @@ -1286,26 +1286,26 @@ def areZRelations(self: _ChordType, other: _ChordType) -> bool: def bass(self, newbass: None = None, *, - find: bool | None = None, + find: bool|None = None, allow_add: bool = False, ) -> pitch.Pitch: return self.pitches[0] # dummy until Astroid 1015 is fixed. @overload def bass(self, - newbass: str | pitch.Pitch | note.Note, + newbass: str|pitch.Pitch|note.Note, *, - find: bool | None = None, + find: bool|None = None, allow_add: bool = False, ) -> None: return None def bass(self, - newbass: None | str | pitch.Pitch | note.Note = None, + newbass: None|str|pitch.Pitch|note.Note = None, *, - find: bool | None = None, + find: bool|None = None, allow_add: bool = False, - ) -> pitch.Pitch | None: + ) -> pitch.Pitch|None: ''' Generally used to find and return the bass Pitch: @@ -1493,7 +1493,7 @@ def canBeTonic(self) -> bool: def closedPosition( self: _ChordType, *, - forceOctave: int | None, + forceOctave: int|None, inPlace: t.Literal[True], leaveRedundantPitches=False ) -> None: @@ -1504,7 +1504,7 @@ def closedPosition( def closedPosition( self: _ChordType, *, - forceOctave: int | None = None, + forceOctave: int|None = None, inPlace: t.Literal[False] = False, leaveRedundantPitches: bool = False ) -> _ChordType: @@ -1514,10 +1514,10 @@ def closedPosition( def closedPosition( self: _ChordType, *, - forceOctave: int | None = None, + forceOctave: int|None = None, inPlace: bool = False, leaveRedundantPitches: bool = False - ) -> _ChordType | None: + ) -> _ChordType|None: ''' Returns a new Chord object with the same pitch classes, but now in closed position. @@ -1880,8 +1880,8 @@ def getChordStep( self, chordStep: int, *, - testRoot: note.Note | pitch.Pitch | None = None - ) -> pitch.Pitch | None: + testRoot: note.Note|pitch.Pitch|None = None + ) -> pitch.Pitch|None: ''' Returns the (first) pitch at the provided scaleDegree (Thus, it's exactly like semitonesFromChordStep, except it instead of the number of @@ -2158,7 +2158,7 @@ def getVolume(self, p): except KeyError: raise ChordException(f'the given pitch is not in the Chord: {p}') - def getZRelation(self) -> Chord | None: + def getZRelation(self) -> Chord|None: ''' Return a Z relation if it exists, otherwise return None. @@ -2305,7 +2305,7 @@ def inversion( newInversion: int, *, find: bool = True, - testRoot: pitch.Pitch | None = None, + testRoot: pitch.Pitch|None = None, transposeOnSet: bool = True ) -> None: return None # dummy until Astroid 1015 is fixed @@ -2316,19 +2316,19 @@ def inversion( newInversion: None = None, *, find: bool = True, - testRoot: pitch.Pitch | None = None, + testRoot: pitch.Pitch|None = None, transposeOnSet: bool = True ) -> int: return -1 # dummy until Astroid 1015 is fixed def inversion( self, - newInversion: int | None = None, + newInversion: int|None = None, *, find: bool = True, - testRoot: pitch.Pitch | None = None, + testRoot: pitch.Pitch|None = None, transposeOnSet: bool = True - ) -> int | None: + ) -> int|None: ''' Find the chord's inversion or (if called with a number) set the chord to the new inversion. @@ -2544,7 +2544,7 @@ def _findInversion(self, rootPitch: pitch.Pitch) -> int: self._cache['inversion'] = inv return inv - def inversionName(self) -> int | None: + def inversionName(self) -> int|None: ''' Returns an integer representing the common abbreviation for the inversion the chord is in. If chord is not in a common inversion, @@ -3807,23 +3807,23 @@ def removeRedundantPitchNames(self, *, inPlace=False): def root(self, newroot: None = None, *, - find: bool | None = None + find: bool|None = None ) -> pitch.Pitch: return self.pitches[0] # dummy until Astroid 1015 is fixed. @overload def root(self, - newroot: str | pitch.Pitch | note.Note, + newroot: str|pitch.Pitch|note.Note, *, - find: bool | None = None + find: bool|None = None ) -> None: return None # dummy until Astroid 1015 is fixed. def root(self, - newroot: None | str | pitch.Pitch | note.Note = None, + newroot: None|str|pitch.Pitch|note.Note = None, *, - find: bool | None = None - ) -> pitch.Pitch | None: + find: bool|None = None + ) -> pitch.Pitch|None: # noinspection PyShadowingNames ''' Returns the root of the chord. Or if given a Pitch as the @@ -4036,10 +4036,10 @@ def semiClosedPosition( def semiClosedPosition( self: _ChordType, *, - forceOctave: int | None = None, - inPlace: t.Literal[True] | t.Literal[False] = False, + forceOctave: int|None = None, + inPlace: t.Literal[True]|t.Literal[False] = False, leaveRedundantPitches: bool = False - ) -> None | _ChordType: + ) -> None|_ChordType: # noinspection PyShadowingNames ''' Similar to :meth:`~music21.chord.Chord.ClosedPosition` in that it @@ -4475,7 +4475,7 @@ def setStemDirection(self, stem, pitchTarget): raise ChordException( f'the given pitch is not in the Chord: {pitchTarget}') - def setTie(self, tieObjOrStr: tie.Tie | str, pitchTarget): + def setTie(self, tieObjOrStr: tie.Tie|str, pitchTarget): ''' Given a tie object (or a tie type string) and a pitch or Note in this Chord, set the pitch's tie attribute in this chord to that tie type. @@ -4546,7 +4546,7 @@ def setTie(self, tieObjOrStr: tie.Tie | str, pitchTarget): def setVolume(self, vol: volume.Volume, - target: str | note.Note | pitch.Pitch): + target: str|note.Note|pitch.Pitch): ''' Set the :class:`~music21.volume.Volume` object of a specific Pitch. @@ -5055,7 +5055,7 @@ def duration(self) -> Duration: >>> c.duration is d True ''' - d = t.cast(Duration | None, self._duration) # type: ignore + d = t.cast(Duration|None, self._duration) # type: ignore if d is None and self._notes: # pitchZeroDuration = self._notes[0]['pitch'].duration pitchZeroDuration = self._notes[0].duration @@ -5079,7 +5079,7 @@ def duration(self, durationObj: Duration): @property # type: ignore @cacheMethod - def fifth(self) -> pitch.Pitch | None: + def fifth(self) -> pitch.Pitch|None: ''' Shortcut for getChordStep(5), but caches it and does not raise exceptions @@ -5739,7 +5739,7 @@ def pitches(self) -> tuple[pitch.Pitch, ...]: return pitches @pitches.setter - def pitches(self, value: Sequence[str | pitch.Pitch | int]): + def pitches(self, value: Sequence[str|pitch.Pitch|int]): self._notes = [] self.clearCache() # TODO: individual ties are not being retained here @@ -6004,7 +6004,7 @@ def seventh(self): @property # type: ignore @cacheMethod - def third(self) -> pitch.Pitch | None: + def third(self) -> pitch.Pitch|None: ''' Shortcut for getChordStep(3), but caches the value, and returns None on errors. @@ -6029,7 +6029,7 @@ def third(self) -> pitch.Pitch | None: -def fromForteClass(notation: str | Sequence[int]) -> Chord: +def fromForteClass(notation: str|Sequence[int]) -> Chord: ''' Return a Chord given a Forte-class notation. The Forte class can be specified as string (e.g., 3-11) or as a list of cardinality and number diff --git a/music21/clef.py b/music21/clef.py index 9a8c2d5e6d..00daf53144 100644 --- a/music21/clef.py +++ b/music21/clef.py @@ -128,9 +128,9 @@ class Clef(base.Music21Object): def __init__(self, **keywords) -> None: super().__init__(**keywords) - self.sign: str | None = None + self.sign: str|None = None # line counts start from the bottom up, the reverse of musedata - self.line: int | None = None + self.line: int|None = None self._octaveChange: int = 0 # set to zero as default # musicxml has an attribute for clefOctaveChange, # an integer to show transposing clef @@ -185,7 +185,7 @@ def name(self) -> str: def getStemDirectionForPitches( self, - pitches: pitch.Pitch | Sequence[pitch.Pitch], + pitches: pitch.Pitch|Sequence[pitch.Pitch], *, firstLastOnly: bool = True, extremePitchOnly: bool = False, @@ -399,7 +399,7 @@ def __init__(self, **keywords): def getStemDirectionForPitches( self, - pitchList: pitch.Pitch | Iterable[pitch.Pitch], + pitchList: pitch.Pitch|Iterable[pitch.Pitch], *, firstLastOnly: bool = True, extremePitchOnly: bool = False, @@ -730,7 +730,7 @@ def __init__(self, **keywords): # ------------------------------------------------------------------------------ -CLASS_FROM_TYPE: dict[str, list[type[Clef] | None]] = { +CLASS_FROM_TYPE: dict[str, list[type[Clef]|None]] = { 'G': [None, FrenchViolinClef, TrebleClef, GSopranoClef, None, None], 'C': [None, SopranoClef, MezzoSopranoClef, AltoClef, TenorClef, CBaritoneClef], 'F': [None, None, None, FBaritoneClef, BassClef, SubBassClef], diff --git a/music21/common/classTools.py b/music21/common/classTools.py index d488c93311..0e0c10062d 100644 --- a/music21/common/classTools.py +++ b/music21/common/classTools.py @@ -88,7 +88,7 @@ def isNum(usrData: t.Any) -> t.TypeGuard[t.Union[float, int, Fraction]]: return False -def isListLike(usrData: t.Any) -> t.TypeGuard[list | tuple]: +def isListLike(usrData: t.Any) -> t.TypeGuard[list|tuple]: ''' Returns True if is a List or Tuple or their subclasses. diff --git a/music21/common/fileTools.py b/music21/common/fileTools.py index b4600ef4c1..55b07452d3 100644 --- a/music21/common/fileTools.py +++ b/music21/common/fileTools.py @@ -55,7 +55,7 @@ def cd(targetDir): os.chdir(cwd) -def readPickleGzip(filePath: str | pathlib.Path) -> t.Any: +def readPickleGzip(filePath: str|pathlib.Path) -> t.Any: ''' Read a gzip-compressed pickle file, uncompress it, unpickle it, and return the contents. diff --git a/music21/common/formats.py b/music21/common/formats.py index c293ef02a2..a79e2b02ea 100644 --- a/music21/common/formats.py +++ b/music21/common/formats.py @@ -57,7 +57,7 @@ # ------------------------------------------------------------------------------ -def findSubConverterForFormat(fmt: str) -> type[SubConverter] | None: +def findSubConverterForFormat(fmt: str) -> type[SubConverter]|None: ''' return a converter.subConverter.SubConverter subclass for a given format -- this is a music21 format name, diff --git a/music21/common/misc.py b/music21/common/misc.py index c1366d9357..60085615f3 100644 --- a/music21/common/misc.py +++ b/music21/common/misc.py @@ -60,7 +60,7 @@ def flattenList(originalList: Iterable[Iterable[_T]]) -> list[_T]: return [item for sublist in originalList for item in sublist] -def unique(originalList: Iterable, *, key: Callable | None = None) -> list: +def unique(originalList: Iterable, *, key: Callable|None = None) -> list: ''' Return a List of unique items from an iterable, preserving order. (unlike casting to a set and back) diff --git a/music21/common/numberTools.py b/music21/common/numberTools.py index 3117b227f2..924f242af8 100644 --- a/music21/common/numberTools.py +++ b/music21/common/numberTools.py @@ -70,7 +70,7 @@ # Number methods... -def numToIntOrFloat(value: OffsetQLIn) -> int | float: +def numToIntOrFloat(value: OffsetQLIn) -> int|float: ''' Given a number, return an integer if it is very close to an integer, otherwise, return a float. @@ -245,11 +245,11 @@ def opFrac(num: int) -> float: pass @overload -def opFrac(num: float | Fraction) -> float | Fraction: +def opFrac(num: float|Fraction) -> float|Fraction: pass # no type checking due to accessing protected attributes (for speed) -def opFrac(num: OffsetQLIn | None) -> OffsetQL | None: +def opFrac(num: OffsetQLIn|None) -> OffsetQL|None: ''' opFrac -> optionally convert a number to a fraction or back. @@ -424,7 +424,7 @@ def mixedNumeral(expr: numbers.Real, return str(0) -def roundToHalfInteger(num: float | int) -> float | int: +def roundToHalfInteger(num: float|int) -> float|int: ''' Given a floating-point number, round to the nearest half-integer. Returns int or float @@ -472,7 +472,7 @@ def roundToHalfInteger(num: float | int) -> float | int: return intVal + floatVal -def addFloatPrecision(x, grain=1e-2) -> float | Fraction: +def addFloatPrecision(x, grain=1e-2) -> float|Fraction: ''' Given a value that suggests a floating point fraction, like 0.33, return a Fraction or float that provides greater specification, such as Fraction(1, 3) @@ -692,7 +692,7 @@ def findSimpleFraction(inner_working): return (int(iy), int(jy)) -def unitNormalizeProportion(values: Sequence[int | float]) -> list[float]: +def unitNormalizeProportion(values: Sequence[int|float]) -> list[float]: ''' Normalize values within the unit interval, where max is determined by the sum of the series. @@ -731,8 +731,8 @@ def unitNormalizeProportion(values: Sequence[int | float]) -> list[float]: def unitBoundaryProportion( - series: Sequence[int | float] -) -> list[tuple[int | float, float]]: + series: Sequence[int|float] +) -> list[tuple[int|float, float]]: ''' Take a series of parts with an implied sum, and create unit-interval boundaries proportional to the series components. @@ -755,7 +755,7 @@ def unitBoundaryProportion( def weightedSelection(values: list[int], - weights: list[int | float], + weights: list[int|float], randomGenerator=None) -> int: ''' Given a list of values and an equal-sized list of weights, @@ -783,7 +783,7 @@ def weightedSelection(values: list[int], return values[index] -def approximateGCD(values: Collection[int | float | Fraction], grain: float = 1e-4) -> float: +def approximateGCD(values: Collection[int|float|Fraction], grain: float = 1e-4) -> float: ''' Given a list of values, find the lowest common divisor of floating point values. diff --git a/music21/common/pathTools.py b/music21/common/pathTools.py index f1bb7bb248..2a50dcdf05 100644 --- a/music21/common/pathTools.py +++ b/music21/common/pathTools.py @@ -28,7 +28,7 @@ import pathlib import unittest -StrOrPath = t.TypeVar('StrOrPath', bound=str | pathlib.Path) +StrOrPath = t.TypeVar('StrOrPath', bound=str|pathlib.Path) # ------------------------------------------------------------------------------ def getSourceFilePath() -> pathlib.Path: @@ -137,7 +137,7 @@ def getRootFilePath() -> pathlib.Path: return fpParent -def relativepath(path: StrOrPath, start: str | None = None) -> StrOrPath | str: +def relativepath(path: StrOrPath, start: str|None = None) -> StrOrPath|str: ''' A cross-platform wrapper for `os.path.relpath()`, which returns `path` if under Windows, otherwise returns the relative path of `path`. @@ -162,17 +162,17 @@ def cleanpath(path: str, *, return '/' # dummy until Astroid #1015 is fixed. @overload -def cleanpath(path: str | pathlib.Path, *, +def cleanpath(path: str|pathlib.Path, *, returnPathlib: t.Literal[True]) -> pathlib.Path: return pathlib.Path('/') # dummy until Astroid #1015 is fixed. @overload -def cleanpath(path: str | pathlib.Path, *, +def cleanpath(path: str|pathlib.Path, *, returnPathlib: t.Literal[False]) -> str: return '/' # dummy until Astroid #1015 is fixed. -def cleanpath(path: str | pathlib.Path, *, - returnPathlib: bool | None = None) -> str | pathlib.Path: +def cleanpath(path: str|pathlib.Path, *, + returnPathlib: bool|None = None) -> str|pathlib.Path: ''' Normalizes the path by expanding ~user on Unix, ${var} environmental vars (is this a good idea?), expanding %name% on Windows, normalizing path names diff --git a/music21/common/types.py b/music21/common/types.py index ae04888b91..8d2eccf662 100644 --- a/music21/common/types.py +++ b/music21/common/types.py @@ -19,10 +19,10 @@ if t.TYPE_CHECKING: import music21 -DocOrder = list[str | Callable] -OffsetQL = float | Fraction -OffsetQLSpecial = float | Fraction | OffsetSpecial -OffsetQLIn = int | float | Fraction +DocOrder = list[str|Callable] +OffsetQL = float|Fraction +OffsetQLSpecial = float|Fraction|OffsetSpecial +OffsetQLIn = int|float|Fraction StreamType = t.TypeVar('StreamType', bound='music21.stream.Stream') StreamType2 = t.TypeVar('StreamType2', bound='music21.stream.Stream') diff --git a/music21/common/weakrefTools.py b/music21/common/weakrefTools.py index b37c61fbc1..8d961720e9 100644 --- a/music21/common/weakrefTools.py +++ b/music21/common/weakrefTools.py @@ -20,7 +20,7 @@ # ------------------------------------------------------------------------------ -def wrapWeakref(referent: _T) -> weakref.ReferenceType | _T: +def wrapWeakref(referent: _T) -> weakref.ReferenceType|_T: ''' utility function that wraps objects as weakrefs but does not wrap already wrapped objects; also prevents wrapping the unwrappable "None" type, etc. @@ -51,7 +51,7 @@ def wrapWeakref(referent: _T) -> weakref.ReferenceType | _T: return referent -def unwrapWeakref(referent: weakref.ReferenceType | t.Any) -> t.Any: +def unwrapWeakref(referent: weakref.ReferenceType|t.Any) -> t.Any: ''' Utility function that gets an object that might be an object itself or a weak reference to an object. It returns obj() if it's a weakref. diff --git a/music21/converter/__init__.py b/music21/converter/__init__.py index 6a0d428eb0..c51751a27b 100644 --- a/music21/converter/__init__.py +++ b/music21/converter/__init__.py @@ -81,7 +81,7 @@ environLocal = environment.Environment('converter') -_StrOrBytes = t.TypeVar('_StrOrBytes', bound=str | bytes) +_StrOrBytes = t.TypeVar('_StrOrBytes', bound=str|bytes) # ------------------------------------------------------------------------------ class ArchiveManagerException(exceptions21.Music21Exception): @@ -129,7 +129,7 @@ class ArchiveManager: # for info on mxl files, see # http://www.recordare.com/xml/compressed-mxl.html - def __init__(self, fp: str | pathlib.Path, archiveType='zip'): + def __init__(self, fp: str|pathlib.Path, archiveType='zip'): self.fp: pathlib.Path = common.cleanpath(fp, returnPathlib=True) self.archiveType: str = archiveType @@ -268,21 +268,21 @@ class PickleFilter: ''' def __init__(self, - fp: str | pathlib.Path, + fp: str|pathlib.Path, forceSource: bool = False, - number: int | None = None, + number: int|None = None, # quantizePost: bool = False, - # quarterLengthDivisors: Iterable[int] | None = None, + # quarterLengthDivisors: Iterable[int]|None = None, **keywords): self.fp: pathlib.Path = common.cleanpath(fp, returnPathlib=True) self.forceSource: bool = forceSource - self.number: int | None = number + self.number: int|None = number self.keywords: dict[str, t.Any] = keywords # environLocal.printDebug(['creating pickle filter']) def getPickleFp(self, - directory: pathlib.Path | str | None = None, - zipType: str | None = None) -> pathlib.Path: + directory: pathlib.Path|str|None = None, + zipType: str|None = None) -> pathlib.Path: ''' Returns the file path of the pickle file for this file. @@ -332,7 +332,7 @@ def removePickle(self) -> None: if pickleFp.exists(): os.remove(pickleFp) - def status(self) -> tuple[pathlib.Path, bool, pathlib.Path | None]: + def status(self) -> tuple[pathlib.Path, bool, pathlib.Path|None]: ''' Given a file path specified with __init__, look for an up-to-date pickled version of this file path. If it exists, return its fp, otherwise return the @@ -385,7 +385,7 @@ def status(self) -> tuple[pathlib.Path, bool, pathlib.Path | None]: # default subConverters to skip _deregisteredSubConverters: deque[ - type[subConverters.SubConverter] | t.Literal['all'] + type[subConverters.SubConverter]|t.Literal['all'] ] = deque() @@ -434,7 +434,7 @@ def registerSubconverter( registerSubConverter(newSubConverter) def unregisterSubConverter( - removeSubConverter: t.Literal['all'] | type[subConverters.SubConverter] + removeSubConverter: t.Literal['all']|type[subConverters.SubConverter] ) -> None: # noinspection PyShadowingNames ''' @@ -513,13 +513,13 @@ class Converter: } def __init__(self) -> None: - self.subConverter: subConverters.SubConverter | None = None + self.subConverter: subConverters.SubConverter|None = None # a stream object unthawed - self._thawedStream: stream.Score | stream.Part | stream.Opus | None = None + self._thawedStream: stream.Score|stream.Part|stream.Opus|None = None def _getDownloadFp( self, - directory: pathlib.Path | str, + directory: pathlib.Path|str, ext: str, url: str, ): @@ -536,9 +536,9 @@ def _getDownloadFp( # noinspection PyShadowingBuiltins def parseFileNoPickle( self, - fp: pathlib.Path | str, - number: int | None = None, - format: str | None = None, + fp: pathlib.Path|str, + number: int|None = None, + format: str|None = None, forceSource: bool = False, **keywords ): @@ -662,7 +662,7 @@ def parseFile(self, fp, number=None, def parseData( self, - dataStr: str | bytes, + dataStr: str|bytes, number=None, format=None, forceSource=False, @@ -725,8 +725,8 @@ def parseURL( self, url: str, *, - format: str | None = None, - number: int | None = None, + format: str|None = None, + number: int|None = None, forceSource: bool = False, **keywords, ) -> None: @@ -1089,7 +1089,7 @@ def setSubConverterFromFormat(self, converterFormat: str): def formatFromHeader( self, dataStr: _StrOrBytes - ) -> tuple[str | None, _StrOrBytes]: + ) -> tuple[str|None, _StrOrBytes]: ''' if dataStr begins with a text header such as "tinyNotation:" then return that format plus the dataStr with the head removed. @@ -1158,7 +1158,7 @@ def formatFromHeader( break return (foundFormat, dataStr) - def regularizeFormat(self, fmt: str) -> str | None: + def regularizeFormat(self, fmt: str) -> str|None: ''' Take in a string representing a format, a file extension (w/ or without leading dot) etc. and find the format string that best represents the format that should be used. @@ -1230,7 +1230,7 @@ def regularizeFormat(self, fmt: str) -> str | None: # -------------------------------------------------------------------------- # properties @property - def stream(self) -> stream.Score | stream.Part | stream.Opus | None: + def stream(self) -> stream.Score|stream.Part|stream.Opus|None: ''' Returns the .subConverter.stream object. ''' @@ -1253,7 +1253,7 @@ def parseFile(fp, number=None, format=None, forceSource=False, - **keywords) -> stream.Score | stream.Part | stream.Opus: + **keywords) -> stream.Score|stream.Part|stream.Opus: ''' Given a file path, attempt to parse the file into a Stream. ''' @@ -1269,7 +1269,7 @@ def parseFile(fp, def parseData(dataStr, number=None, format=None, - **keywords) -> stream.Score | stream.Part | stream.Opus: + **keywords) -> stream.Score|stream.Part|stream.Opus: ''' Given musical data represented within a Python string, attempt to parse the data into a Stream. @@ -1287,7 +1287,7 @@ def parseURL(url, format=None, number=None, forceSource=False, - **keywords) -> stream.Score | stream.Part | stream.Opus: + **keywords) -> stream.Score|stream.Part|stream.Opus: ''' Given a URL, attempt to download and parse the file into a Stream. Note: URL downloading will not happen automatically unless the user has set their @@ -1302,12 +1302,12 @@ def parseURL(url, return v.stream -def parse(value: bundles.MetadataEntry | bytes | str | pathlib.Path | list | tuple, +def parse(value: bundles.MetadataEntry|bytes|str|pathlib.Path|list|tuple, *, forceSource: bool = False, - number: int | None = None, - format: str | None = None, # pylint: disable=redefined-builtin - **keywords) -> stream.Score | stream.Part | stream.Opus: + number: int|None = None, + format: str|None = None, # pylint: disable=redefined-builtin + **keywords) -> stream.Score|stream.Part|stream.Opus: r''' Given a file path, encoded data in a Python string, or a URL, attempt to parse the item into a Stream. Note: URL downloading will not happen @@ -1424,7 +1424,7 @@ def parse(value: bundles.MetadataEntry | bytes | str | pathlib.Path | list | tup # all else, including MidiBytes return parseData(value, number=number, format=format, **keywords) -def toData(obj: base.Music21Object, fmt: str, **keywords) -> str | bytes: +def toData(obj: base.Music21Object, fmt: str, **keywords) -> str|bytes: ''' Convert `obj` to the given format `fmt` and return the information retrieved. diff --git a/music21/converter/museScore.py b/music21/converter/museScore.py index 4a94f54ca8..6f8696d9b1 100644 --- a/music21/converter/museScore.py +++ b/music21/converter/museScore.py @@ -32,7 +32,7 @@ def runThroughMuseScore( fp, subformats=(), *, - dpi: int | None = None, + dpi: int|None = None, trimEdges: bool = True, leaveMargin: int = 0, **keywords @@ -101,7 +101,7 @@ def runThroughMuseScore( -def findNumberedPNGPath(inputFp: str | pathlib.Path) -> pathlib.Path: +def findNumberedPNGPath(inputFp: str|pathlib.Path) -> pathlib.Path: ''' Find the first numbered file path corresponding to the provided unnumbered file path ending in ".png". Raises an exception if no file can be found. @@ -149,7 +149,7 @@ def findLastPNGPath(inputFp: pathlib.Path) -> pathlib.Path: def findPNGRange( firstFp: pathlib.Path, - lastFp: pathlib.Path | None = None + lastFp: pathlib.Path|None = None ) -> tuple[int, int]: ''' Return a 2-tuple of the maximum PNG number and the number of digits used to diff --git a/music21/converter/subConverters.py b/music21/converter/subConverters.py index 119060b156..65e87f1101 100644 --- a/music21/converter/subConverters.py +++ b/music21/converter/subConverters.py @@ -72,16 +72,16 @@ class SubConverter: registerInputExtensions: tuple[str, ...] = () # if converter supports input registerOutputExtensions: tuple[str, ...] = () # if converter supports output registerOutputSubformatExtensions: dict[str, str] = {} - launchKey: str | pathlib.Path | None = None + launchKey: str|pathlib.Path|None = None codecWrite: bool = False stringEncoding: str = 'utf-8' def __init__(self, **keywords) -> None: - self._stream: stream.Score | stream.Part | stream.Opus = stream.Score() + self._stream: stream.Score|stream.Part|stream.Opus = stream.Score() self.keywords: dict[str, t.Any] = keywords - def parseData(self, dataString, number: int | None = None): + def parseData(self, dataString, number: int|None = None): ''' Called when a string (or binary) data is encountered. @@ -93,8 +93,8 @@ def parseData(self, dataString, number: int | None = None): # return self.stream def parseFile(self, - filePath: str | pathlib.Path, - number: int | None = None, + filePath: str|pathlib.Path, + number: int|None = None, **keywords): ''' Called when a file is encountered. If all that needs to be done is @@ -139,7 +139,7 @@ def launch(self, filePath: pathlib.Path, fmt=None, options: str = '', - app: str | None = None, + app: str|None = None, launchKey=None): # pragma: no cover ''' Opens the appropriate viewer for the file generated by .write() @@ -212,7 +212,7 @@ def launch(self, def show( self, obj, - fmt: str | None, + fmt: str|None, app=None, subformats=(), **keywords @@ -268,8 +268,8 @@ def getTemporaryFile(self, subformats: Iterable[str] = ()) -> pathlib.Path: def write(self, obj: music21.base.Music21Object, - fmt: str | None, - fp: str | pathlib.Path | IOBase | None = None, + fmt: str|None, + fp: str|pathlib.Path|IOBase|None = None, subformats: Iterable[str] = (), **keywords): # pragma: no cover ''' @@ -280,8 +280,8 @@ def write(self, return fp def writeDataStream(self, - fp: str | pathlib.Path | IOBase | None, - dataStr: str | bytes, + fp: str|pathlib.Path|IOBase|None, + dataStr: str|bytes, **keywords) -> pathlib.Path: # pragma: no cover ''' Writes the data stream to `fp` or to a temporary file and returns the @@ -322,10 +322,10 @@ def writeDataStream(self, def toData( self, obj, - fmt: str | None, + fmt: str|None, subformats: Iterable[str] = (), **keywords, - ) -> str | bytes: + ) -> str|bytes: ''' Write the object out in the given format and then read it back in and return the object (str or bytes) returned. @@ -576,7 +576,7 @@ class ConverterVolpiano(SubConverter): def parseData( self, dataString, - number: int | None = None, + number: int|None = None, *, breaksToLayout: bool = False, **keywords, @@ -663,8 +663,8 @@ def parseData(self, humdrumString, number=None): return self.data def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): ''' Open Humdrum data from a file path. @@ -777,8 +777,8 @@ def parseData(self, nwcData): self.stream = noteworthyTranslate.NoteworthyTranslator().parseString(nwcData) def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): # noinspection SpellCheckingInspection,PyShadowingNames ''' @@ -814,8 +814,8 @@ def parseData(self, nwcData): # pragma: no cover self.stream = noteworthyBinary.NWCConverter().parseString(nwcData) def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): from music21.noteworthy import binaryTranslate as noteworthyBinary self.stream = noteworthyBinary.NWCConverter().parseFile(filePath) @@ -847,8 +847,8 @@ def parseData(self, xmlString: str, number=None): self.stream = c.stream def parseFile(self, - filePath: str | pathlib.Path, - number: int | None = None, + filePath: str|pathlib.Path, + number: int|None = None, **keywords): ''' Open from a file path; check to see if there is a pickled @@ -881,7 +881,7 @@ def parseFile(self, def writeDataStream(self, fp, - dataStr: str | bytes, + dataStr: str|bytes, **keywords) -> pathlib.Path: # pragma: no cover # noinspection PyShadowingNames ''' @@ -934,7 +934,7 @@ def write(self, subformats=(), *, makeNotation=True, - compress: bool | None = None, + compress: bool|None = None, **keywords): ''' Write to a .musicxml file. @@ -1038,8 +1038,8 @@ def parseData(self, strData, number=None): self.stream = midiTranslate.midiStringToStream(strData, **self.keywords) def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): ''' Get MIDI data from a file path. @@ -1103,8 +1103,8 @@ def parseData(self, strData, number=None): abcFormat.translate.abcToStreamScore(abcHandler, self.stream) def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): ''' Get ABC data from a file path. If more than one work is defined in the ABC @@ -1155,8 +1155,8 @@ def parseData(self, strData, number=None): romanTextTranslate.romanTextToStreamScore(rtHandler, self.stream) def parseFile(self, - filePath: pathlib.Path | str, - number: int | None = None, + filePath: pathlib.Path|str, + number: int|None = None, **keywords): from music21.romanText import rtObjects from music21.romanText import translate as romanTextTranslate @@ -1196,13 +1196,13 @@ class ConverterClercqTemperley(SubConverter): registerFormats = ('cttxt', 'har', 'clercqTemperley') registerInputExtensions = ('cttxt', 'har', 'clercqTemperley') - def parseData(self, strData: str | pathlib.Path, number=None): + def parseData(self, strData: str|pathlib.Path, number=None): from music21.romanText import clercqTemperley ctSong = clercqTemperley.CTSong(strData) self.stream = ctSong.toPart() def parseFile(self, - filePath: pathlib.Path | str, + filePath: pathlib.Path|str, number=None, **keywords): self.parseData(filePath) @@ -1229,8 +1229,8 @@ def parseData(self, strData, number=None): self.stream = partScore def parseFile(self, - filePath: str | pathlib.Path, - number: int | None = None, + filePath: str|pathlib.Path, + number: int|None = None, **keywords): ''' Parse a Capella file @@ -1268,8 +1268,8 @@ def parseData(self, strData, number=None): # pragma: no cover musedataTranslate.museDataWorkToStreamScore(mdw, self.stream) def parseFile(self, - filePath: str | pathlib.Path, - number: int | None = None, + filePath: str|pathlib.Path, + number: int|None = None, **keywords): ''' parse fp (a pathlib.Path()) and number @@ -1344,8 +1344,8 @@ def parseData(self, dataString: str, number=None) -> stream.Stream: def parseFile( self, - filePath: str | pathlib.Path, - number: int | None = None, + filePath: str|pathlib.Path, + number: int|None = None, **keywords, ) -> stream.Stream: ''' diff --git a/music21/corpus/__init__.py b/music21/corpus/__init__.py index 4c09f60418..ebc5b5812a 100644 --- a/music21/corpus/__init__.py +++ b/music21/corpus/__init__.py @@ -276,10 +276,10 @@ def noCorpus(): def getWork( workName: str, - movementNumber: int | None = None, + movementNumber: int|None = None, *, fileExtensions: Iterable[str] = () -) -> pathlib.Path | list[pathlib.Path]: +) -> pathlib.Path|list[pathlib.Path]: ''' Search all Corpora for a work, and return a file path. N.B. does not parse the work: but it's suitable for passing @@ -320,13 +320,13 @@ def getWork( # pylint: disable=redefined-builtin # noinspection PyShadowingBuiltins def parse( - workName: str | pathlib.Path, - movementNumber: int | None = None, + workName: str|pathlib.Path, + movementNumber: int|None = None, *, - number: int | None = None, + number: int|None = None, fileExtensions: Iterable[str] = (), forceSource: bool = False, - format: str | None = None + format: str|None = None ): ''' The most important method call for corpus. diff --git a/music21/corpus/chorales.py b/music21/corpus/chorales.py index a9ef814146..51506b75bc 100644 --- a/music21/corpus/chorales.py +++ b/music21/corpus/chorales.py @@ -1068,15 +1068,15 @@ class Iterator: 'titleList', 'numberList', 'returnType', 'iterationType'] def __init__(self, - currentNumber: int | None = None, - highestNumber: int | None = None, + currentNumber: int|None = None, + highestNumber: int|None = None, *, numberingSystem: str = 'riemenschneider', returnType: str = 'stream', iterationType: str = 'number', analysis: bool = False, - numberList: list[int] | None = None, - titleList: list[str] | None = None, + numberList: list[int]|None = None, + titleList: list[str]|None = None, ): ''' By default: numberingSystem = 'riemenschneider', currentNumber = 1, diff --git a/music21/corpus/corpora.py b/music21/corpus/corpora.py index 3e658c7d27..f66f613c67 100644 --- a/music21/corpus/corpora.py +++ b/music21/corpus/corpora.py @@ -58,7 +58,7 @@ class Corpus(prebase.ProtoM21Object): _pathsCache: dict[tuple[str, tuple[str, ...]], list[pathlib.Path]] = {} - _directoryInformation: tuple[()] | Sequence[tuple[str, str, bool]] = () + _directoryInformation: tuple[()]|Sequence[tuple[str, str, bool]] = () parseUsingCorpus = True @@ -265,8 +265,8 @@ def getPaths( def getWorkList( self, - workName: str | pathlib.Path, - movementNumber: int | Collection[int] | None = None, + workName: str|pathlib.Path, + movementNumber: int|Collection[int]|None = None, *, fileExtensions: Iterable[str] = (), ): @@ -376,7 +376,7 @@ def getWorkList( def search( self, query: str, - field: str | None = None, + field: str|None = None, *, fileExtensions: Iterable[str] = (), **keywords @@ -732,7 +732,7 @@ class LocalCorpus(Corpus): # INITIALIZER # - def __init__(self, name: str | None = None): + def __init__(self, name: str|None = None): if not isinstance(name, (str, type(None))): raise CorpusException('Name must be a string or None') @@ -882,7 +882,7 @@ def getPaths( return Corpus._pathsCache[cacheKey] - def removePath(self, directoryPath: str | pathlib.Path) -> None: + def removePath(self, directoryPath: str|pathlib.Path) -> None: r''' Remove a directory path from a local corpus. diff --git a/music21/corpus/manager.py b/music21/corpus/manager.py index 0629f2a3d5..fa23b1266d 100644 --- a/music21/corpus/manager.py +++ b/music21/corpus/manager.py @@ -38,7 +38,7 @@ from music21 import stream -_metadataBundles: dict[str, bundles.MetadataBundle | None] = { +_metadataBundles: dict[str, bundles.MetadataBundle|None] = { 'core': None, 'local': None, # 'virtual': None, @@ -123,11 +123,11 @@ def iterateCorpora(returnObjects=True): def getWork( - workName: str | pathlib.Path, - movementNumber: int | None = None, + workName: str|pathlib.Path, + movementNumber: int|None = None, *, fileExtensions: Iterable[str] = (), -) -> pathlib.Path | list[pathlib.Path]: +) -> pathlib.Path|list[pathlib.Path]: ''' this parse function is called from `corpus.parse()` and does nothing differently from it. @@ -178,14 +178,14 @@ def getWork( # pylint: disable=redefined-builtin # noinspection PyShadowingBuiltins def parse( - workName: str | pathlib.Path, + workName: str|pathlib.Path, *, - movementNumber: int | None = None, - number: int | None = None, + movementNumber: int|None = None, + number: int|None = None, fileExtensions: Iterable[str] = (), forceSource: bool = False, - format: str | None = None, -) -> stream.Score | stream.Part | stream.Opus: + format: str|None = None, +) -> stream.Score|stream.Part|stream.Opus: filePaths = getWork( workName=workName, movementNumber=movementNumber, @@ -236,11 +236,11 @@ def _addCorpusFilePathToStreamObject(streamObj, filePath): def search( - query: str | None = None, - field: str | None = None, + query: str|None = None, + field: str|None = None, *, corpusNames=None, - fileExtensions: Iterable[str] | str = (), + fileExtensions: Iterable[str]|str = (), **keywords ): ''' diff --git a/music21/derivation.py b/music21/derivation.py index a6685239ac..c9a4aa7b4b 100644 --- a/music21/derivation.py +++ b/music21/derivation.py @@ -149,14 +149,14 @@ class Derivation(SlottedObjectMixin): # INITIALIZER # - def __init__(self, client: base.Music21Object | None = None): + def __init__(self, client: base.Music21Object|None = None): # store a reference to the Music21Object that has this Derivation object as a property - self._client: weakref.ReferenceType | None = None - self._clientId: int | None = None # store python-id to optimize w/o unwrapping - self._method: str | None = None + self._client: weakref.ReferenceType|None = None + self._clientId: int|None = None # store python-id to optimize w/o unwrapping + self._method: str|None = None # origin should be stored as a weak ref -- the place where the client was derived from. self._origin = None - self._originId: int | None = None # store id to optimize w/o unwrapping + self._originId: int|None = None # store id to optimize w/o unwrapping # set client; can handle None self.client = client @@ -195,7 +195,7 @@ def __setstate__(self, state): # PUBLIC PROPERTIES # @property - def client(self) -> base.Music21Object | None: + def client(self) -> base.Music21Object|None: c = common.unwrapWeakref(self._client) if c is None and self._clientId is not None: self._clientId = None @@ -205,7 +205,7 @@ def client(self) -> base.Music21Object | None: return c @client.setter - def client(self, client: base.Music21Object | None): + def client(self, client: base.Music21Object|None): # client is the Stream that this derivation lives on if client is None: self._clientId = None @@ -246,7 +246,7 @@ def chain(self) -> Generator[base.Music21Object, None, None]: origin = origin.derivation.origin @property - def method(self) -> str | None: + def method(self) -> str|None: ''' Returns or sets the string of the method that was used to generate this Stream. @@ -286,15 +286,15 @@ def method(self) -> str | None: return self._method @method.setter - def method(self, method: str | None): + def method(self, method: str|None): self._method = method @property - def origin(self) -> base.Music21Object | None: + def origin(self) -> base.Music21Object|None: return self._origin @origin.setter - def origin(self, origin: base.Music21Object | None): + def origin(self, origin: base.Music21Object|None): # for now, origin is not a weak ref if origin is None: self._originId = None @@ -305,7 +305,7 @@ def origin(self, origin: base.Music21Object | None): # self._origin = common.wrapWeakref(origin) @property - def originId(self) -> int | None: + def originId(self) -> int|None: ''' Return the Python id (=memory location) of the origin. (Same as id(derivation.origin). Not the same as derivation.origin.ind) @@ -313,7 +313,7 @@ def originId(self) -> int | None: return self._originId @property - def rootDerivation(self) -> base.Music21Object | None: + def rootDerivation(self) -> base.Music21Object|None: r''' Return a reference to the oldest source of this Stream; that is, chain calls to :attr:`~music21.stream.Stream.derivesFrom` until we get to a diff --git a/music21/duration.py b/music21/duration.py index 16e37ab8b2..fe32f4a64c 100644 --- a/music21/duration.py +++ b/music21/duration.py @@ -165,7 +165,7 @@ class TupletException(exceptions21.Music21Exception): class QuarterLengthConversion(t.NamedTuple): components: tuple[DurationTuple] - tuplet: Tuplet | None + tuplet: Tuplet|None def unitSpec(durationObjectOrObjects): @@ -349,7 +349,7 @@ def convertQuarterLengthToType(qLen: OffsetQLIn) -> str: def dottedMatch(qLen: OffsetQLIn, maxDots=4 - ) -> tuple[int, str] | tuple[t.Literal[False], t.Literal[False]]: + ) -> tuple[int, str]|tuple[t.Literal[False], t.Literal[False]]: ''' Given a quarterLength, determine if there is a dotted (or non-dotted) type that exactly matches. Returns a pair of @@ -739,7 +739,7 @@ def quarterConversion(qLen: OffsetQLIn) -> QuarterLengthConversion: def convertTypeToQuarterLength( dType: str, dots=0, - tuplets: list[Tuplet] | None = None, + tuplets: list[Tuplet]|None = None, dotGroups=None ) -> OffsetQL: # noinspection PyShadowingNames @@ -1063,8 +1063,8 @@ def __init__( self, numberNotesActual: int = 3, numberNotesNormal: int = 2, - durationActual: DurationTuple | Duration | str | tuple[str, int] | None = None, - durationNormal: DurationTuple | Duration | str | tuple[str, int] | None = None, + durationActual: DurationTuple|Duration|str|tuple[str, int]|None = None, + durationNormal: DurationTuple|Duration|str|tuple[str, int]|None = None, *, tupletId: int = 0, nestedLevel: int = 1, @@ -1079,8 +1079,8 @@ def __init__( self.frozen = False # environLocal.printDebug(['creating Tuplet instance']) - self._durationNormal: DurationTuple | None = None - self._durationActual: DurationTuple | None = None + self._durationNormal: DurationTuple|None = None + self._durationActual: DurationTuple|None = None # necessary for some complex tuplets, interrupted, for instance self.tupletId = tupletId @@ -1210,7 +1210,7 @@ def _checkFrozen(self): 'A frozen tuplet (or one attached to a duration) has immutable length.') # PUBLIC METHODS # - def augmentOrDiminish(self, amountToScale: int | float): + def augmentOrDiminish(self, amountToScale: int|float): ''' Given a number greater than zero, multiplies the current quarterLength of the @@ -1268,7 +1268,7 @@ def augmentOrDiminish(self, amountToScale: int | float): def setDurationType( self, - durType: str | int | float | fractions.Fraction, + durType: str|int|float|fractions.Fraction, dots=0 ): ''' @@ -1413,7 +1413,7 @@ def tupletMultiplier(self) -> OffsetQL: # PUBLIC PROPERTIES # @property - def durationActual(self) -> DurationTuple | None: + def durationActual(self) -> DurationTuple|None: ''' durationActual is a DurationTuple that represents the notes that are actually present and counted in a tuplet. For instance, in a 7 @@ -1437,7 +1437,7 @@ def durationActual(self) -> DurationTuple | None: return self._durationActual @durationActual.setter - def durationActual(self, dA: DurationTuple | Duration | str | None): + def durationActual(self, dA: DurationTuple|Duration|str|None): self._checkFrozen() if isinstance(dA, DurationTuple) or dA is None: @@ -1451,7 +1451,7 @@ def durationActual(self, dA: DurationTuple | Duration | str | None): self._durationActual = durationTupleFromTypeDots(dA, dots=0) @property - def durationNormal(self) -> DurationTuple | None: + def durationNormal(self) -> DurationTuple|None: ''' durationNormal is a DurationTuple that represents the notes that would be present in the space normally (if there were no tuplets). For instance, in a 7 @@ -1475,7 +1475,7 @@ def durationNormal(self) -> DurationTuple | None: return self._durationNormal @durationNormal.setter - def durationNormal(self, dN: DurationTuple | Duration | str | None): + def durationNormal(self, dN: DurationTuple|Duration|str|None): self._checkFrozen() if isinstance(dN, DurationTuple) or dN is None: self._durationNormal = dN @@ -1661,28 +1661,28 @@ class Duration(prebase.ProtoM21Object, SlottedObjectMixin): # INITIALIZER # def __init__(self, - typeOrDuration: str | OffsetQLIn | DurationTuple | None = None, + typeOrDuration: str|OffsetQLIn|DurationTuple|None = None, /, *, - type: str | None = None, # pylint: disable=redefined-builtin - dots: int | None = 0, - quarterLength: OffsetQLIn | None = None, - durationTuple: DurationTuple | None = None, - components: Iterable[DurationTuple] | None = None, - client: base.Music21Object | None = None, + type: str|None = None, # pylint: disable=redefined-builtin + dots: int|None = 0, + quarterLength: OffsetQLIn|None = None, + durationTuple: DurationTuple|None = None, + components: Iterable[DurationTuple]|None = None, + client: base.Music21Object|None = None, **keywords): # First positional argument is assumed to be type string or a quarterLength. # no need for super() on ProtoM21 or SlottedObjectMixin # store a reference to the object that has this duration object as a property # Will assign at end, so as not to informClient during creation. - self.client: base.Music21Object | None = None + self.client: base.Music21Object|None = None self._componentsNeedUpdating = False self._quarterLengthNeedsUpdating = False self._typeNeedsUpdating = False - self._unlinkedType: str | None = None + self._unlinkedType: str|None = None self._dotGroups: tuple[int, ...] = (0,) self._tuplets: tuple['Tuplet', ...] = () # an empty tuple self._qtrLength: OffsetQL = 0.0 @@ -1877,7 +1877,7 @@ def _setLinked(self, value: bool): linked = property(_getLinked, _setLinked) def addDurationTuple(self, - dur: DurationTuple | Duration | str | OffsetQLIn, + dur: DurationTuple|Duration|str|OffsetQLIn, *, _skipInform=False): ''' @@ -2253,7 +2253,7 @@ def consolidate(self): def getGraceDuration( self, appoggiatura=False - ) -> GraceDuration | AppoggiaturaDuration: + ) -> GraceDuration|AppoggiaturaDuration: # noinspection PyShadowingNames ''' Return a deepcopy of this Duration as a GraceDuration instance with the same types. @@ -2855,7 +2855,7 @@ def isComplex(self) -> bool: return False @property - def ordinal(self) -> int | str | None: + def ordinal(self) -> int|str|None: ''' Get the ordinal value of the Duration, where whole is 4, half is 5, etc. @@ -3178,7 +3178,7 @@ class GraceDuration(Duration): # INITIALIZER # def __init__(self, - typeOrDuration: str | OffsetQLIn | DurationTuple | None = None, + typeOrDuration: str|OffsetQLIn|DurationTuple|None = None, **keywords): super().__init__(typeOrDuration, **keywords) # update components to derive types; this sets ql, but this @@ -3198,8 +3198,8 @@ def __init__(self, self._slash = None self.slash = True # can be True, False, or None; make None go to True? # values are unit interval percentages - self.stealTimePrevious: float | None = None - self.stealTimeFollowing: float | None = None + self.stealTimePrevious: float|None = None + self.stealTimeFollowing: float|None = None # PUBLIC PROPERTIES # @@ -3245,7 +3245,7 @@ class AppoggiaturaDuration(GraceDuration): # INITIALIZER # def __init__(self, - typeOrDuration: str | OffsetQLIn | DurationTuple | None = None, + typeOrDuration: str|OffsetQLIn|DurationTuple|None = None, **keywords): super().__init__(typeOrDuration, **keywords) self.slash = False # can be True, False, or None; make None go to True? @@ -3269,8 +3269,8 @@ class TupletFixer: :meth:`~music21.duration.TupletFixer.fixBrokenTupletDuration` for demonstrations. ''' - def __init__(self, streamIn: stream.Stream | None = None): - self.streamIn: stream.Stream | None = streamIn + def __init__(self, streamIn: stream.Stream|None = None): + self.streamIn: stream.Stream|None = streamIn self.allTupletGroups: list[list[note.GeneralNote]] = [] def setStream(self, streamIn: stream.Stream) -> None: diff --git a/music21/environment.py b/music21/environment.py index 5077eb22d7..84f9793d2f 100644 --- a/music21/environment.py +++ b/music21/environment.py @@ -437,7 +437,7 @@ def _loadDefaults(self, forcePlatform=None): ]: self[name] = value # use for key checking - def _checkAccessibility(self, path: str | pathlib.Path | None) -> bool: + def _checkAccessibility(self, path: str|pathlib.Path|None) -> bool: ''' Return True if the path exists, is readable and writable. ''' @@ -650,7 +650,7 @@ def getSettingsPath(self): # darwin specific option # os.path.join(os.environ['HOME'], 'Library',) - def getTempFile(self, suffix='', returnPathlib=True) -> str | pathlib.Path: + def getTempFile(self, suffix='', returnPathlib=True) -> str|pathlib.Path: ''' Gets a temporary file with a suffix that will work for a bit. @@ -1011,7 +1011,7 @@ def getTempFile(self, suffix: str, returnPathlib: t.Literal[False]) -> str: def getTempFile(self, suffix: str = '', returnPathlib: t.Literal[True] = True) -> pathlib.Path: return pathlib.Path('/') # astroid #1015 - def getTempFile(self, suffix: str = '', returnPathlib=True) -> str | pathlib.Path: + def getTempFile(self, suffix: str = '', returnPathlib=True) -> str|pathlib.Path: ''' Return a file path to a temporary file with the specified suffix (file extension). diff --git a/music21/expressions.py b/music21/expressions.py index f3ad12d532..8fe3a672e7 100644 --- a/music21/expressions.py +++ b/music21/expressions.py @@ -54,9 +54,9 @@ def isUnison(intv: interval.IntervalBase) -> bool: return False def realizeOrnaments( - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None + keySig: key.KeySignature|None = None ): ''' given a Note or Unpitched with Ornament expressions, @@ -74,7 +74,7 @@ def realizeOrnaments( .. image:: images/expressionsMordentRealize.* :width: 218 ''' - srcObject: note.Note | note.Unpitched | None = srcObj + srcObject: note.Note|note.Unpitched|None = srcObj if t.TYPE_CHECKING: # it comes in as not None assert srcObject is not None @@ -199,7 +199,7 @@ def _reprInternal(self): return repr(self.content) @staticmethod - def _getNumberingFromContent(c) -> str | None: + def _getNumberingFromContent(c) -> str|None: ''' if numbering was not set, get it from the content @@ -389,7 +389,7 @@ def _reprInternal(self): return '' @property - def enclosure(self) -> style.Enclosure | None: + def enclosure(self) -> style.Enclosure|None: ''' Returns or sets the enclosure on the Style object stored on .style. @@ -415,7 +415,7 @@ def enclosure(self) -> style.Enclosure | None: return self.style.enclosure @enclosure.setter - def enclosure(self, value: style.Enclosure | None): + def enclosure(self, value: style.Enclosure|None): if not self.hasStyleInformation and value is None: return self.style.enclosure = value @@ -490,13 +490,13 @@ def __init__(self, **keywords) -> None: def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: ''' subclassable method call that takes a sourceObject and optional keySig and returns a three-element tuple of a list of notes before the @@ -517,11 +517,11 @@ def realize( def fillListOfRealizedNotes( self, - srcObj: note.Note | note.Unpitched, - fillObjects: list[note.Note | note.Unpitched], + srcObj: note.Note|note.Unpitched, + fillObjects: list[note.Note|note.Unpitched], transposeInterval: interval.IntervalBase, *, - useQL: OffsetQL | None = None + useQL: OffsetQL|None = None ) -> None: ''' Used by trills and mordents to fill out their realization. @@ -554,7 +554,7 @@ def resolveOrnamentalPitches( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None + keySig: key.KeySignature|None = None ): ''' Only implemented in Turn, GeneralMordent, and Trill. @@ -571,10 +571,10 @@ def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]: def updateAccidentalDisplay( self, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, @@ -593,9 +593,9 @@ class GeneralMordent(Ornament): ''' _direction: str = '' # up or down - def __init__(self, *, accidental: pitch.Accidental | None = None, **keywords): + def __init__(self, *, accidental: pitch.Accidental|None = None, **keywords): super().__init__(**keywords) - self._accidental: pitch.Accidental | None = accidental + self._accidental: pitch.Accidental|None = accidental self.quarterLength = 0.125 # 32nd note default self.placement = 'above' @@ -624,14 +624,14 @@ def name(self) -> str: return theName @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: ''' This is the GeneralMordent's accidental. ''' return self._accidental @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): self._accidental = newAccidental @property @@ -646,7 +646,7 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: ''' Returns the size of the mordent's interval, given a source note and @@ -695,7 +695,7 @@ def resolveOrnamentalPitches( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None + keySig: key.KeySignature|None = None ): ''' Computes and stores the ornamental pitch for a GeneralMordent, given the srcObj @@ -762,7 +762,7 @@ def resolveOrnamentalPitches( self._ornamentalPitches = (ornamentalPitch,) @property - def ornamentalPitch(self) -> pitch.Pitch | None: + def ornamentalPitch(self) -> pitch.Pitch|None: ''' Returns the mordent's ornamentalPitch. If resolveOrnamentalPitches has not yet been called, None is returned. @@ -783,10 +783,10 @@ def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]: def updateAccidentalDisplay( self, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, @@ -822,13 +822,13 @@ def updateAccidentalDisplay( def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: ''' Realize a mordent. @@ -864,7 +864,7 @@ def realize( raise ExpressionException('The note is not long enough to realize a mordent') use_ql = srcObj.duration.quarterLength / 4 - currentKeySig: key.KeySignature | None = keySig + currentKeySig: key.KeySignature|None = keySig if currentKeySig is None: currentKeySig = srcObj.getContextByClass(key.KeySignature) if currentKeySig is None: @@ -872,7 +872,7 @@ def realize( remainderQL = srcObj.duration.quarterLength - (2 * use_ql) transposeInterval = self.getSize(srcObj, keySig=currentKeySig) - mordNotes: list[note.Note | note.Unpitched] = [] + mordNotes: list[note.Note|note.Unpitched] = [] self.fillListOfRealizedNotes(srcObj, mordNotes, transposeInterval, useQL=use_ql) isTransposed: bool = not isUnison(transposeInterval) @@ -993,16 +993,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._minorSecondDown @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of HalfStepMordent') @@ -1027,16 +1027,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._majorSecondDown @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of WholeStepMordent') @@ -1105,16 +1105,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._minorSecondUp @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of HalfStepInvertedMordent') @@ -1140,16 +1140,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._majorSecondUp @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of WholeStepInvertedMordent') @@ -1191,9 +1191,9 @@ class Trill(Ornament): ''' _direction: str = 'up' - def __init__(self, *, accidental: pitch.Accidental | None = None, **keywords) -> None: + def __init__(self, *, accidental: pitch.Accidental|None = None, **keywords) -> None: super().__init__(**keywords) - self._accidental: pitch.Accidental | None = accidental + self._accidental: pitch.Accidental|None = accidental self.placement = 'above' self.nachschlag = False # play little notes at the end of the trill? self.tieAttach = 'all' @@ -1232,7 +1232,7 @@ def direction(self) -> str: return self._direction @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: ''' This is the Trill's accidental. Whether or not it is visible is dictated by the accidental's displayStatus. @@ -1240,7 +1240,7 @@ def accidental(self) -> pitch.Accidental | None: return self._accidental @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): self._accidental = newAccidental def splitClient(self, noteList): @@ -1269,7 +1269,7 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: ''' Returns the size of the trill's interval, given a source note and @@ -1317,7 +1317,7 @@ def resolveOrnamentalPitches( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None + keySig: key.KeySignature|None = None ): ''' Computes and stores the ornamental pitch for a Trill, given the srcObj @@ -1364,7 +1364,7 @@ def resolveOrnamentalPitches( self._ornamentalPitches = (ornamentalPitch,) @property - def ornamentalPitch(self) -> pitch.Pitch | None: + def ornamentalPitch(self) -> pitch.Pitch|None: ''' Returns the trill's ornamentalPitch. If resolveOrnamentalPitches has not yet been called, None is returned. @@ -1385,10 +1385,10 @@ def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]: def updateAccidentalDisplay( self, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, @@ -1493,13 +1493,13 @@ def updateAccidentalDisplay( def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: ''' realize a trill. @@ -1622,7 +1622,7 @@ def realize( if self.nachschlag: numberOfTrillNotes -= 2 - trillNotes: list[note.Note | note.Unpitched] = [] + trillNotes: list[note.Note|note.Unpitched] = [] for unused_counter in range(int(numberOfTrillNotes / 2)): self.fillListOfRealizedNotes(srcObj, trillNotes, transposeInterval, useQL=useQL) @@ -1711,16 +1711,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._minorSecondUp @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of HalfStepTrill') @@ -1759,16 +1759,16 @@ def getSize( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: return self._majorSecondUp @property - def accidental(self) -> pitch.Accidental | None: + def accidental(self) -> pitch.Accidental|None: return None @accidental.setter - def accidental(self, newAccidental: pitch.Accidental | None): + def accidental(self, newAccidental: pitch.Accidental|None): raise ExpressionException('Cannot set accidental of WholeStepTrill') @@ -1819,22 +1819,22 @@ class Turn(Ornament): def __init__( self, *, - delay: OrnamentDelay | OffsetQL = OrnamentDelay.NO_DELAY, - upperAccidental: pitch.Accidental | None = None, - lowerAccidental: pitch.Accidental | None = None, + delay: OrnamentDelay|OffsetQL = OrnamentDelay.NO_DELAY, + upperAccidental: pitch.Accidental|None = None, + lowerAccidental: pitch.Accidental|None = None, **keywords ): super().__init__(**keywords) - self._upperAccidental: pitch.Accidental | None = upperAccidental - self._lowerAccidental: pitch.Accidental | None = lowerAccidental + self._upperAccidental: pitch.Accidental|None = upperAccidental + self._lowerAccidental: pitch.Accidental|None = lowerAccidental self.placement: str = 'above' self.tieAttach: str = 'all' self.quarterLength: OffsetQL = 0.25 - self._delay: OrnamentDelay | OffsetQL = 0.0 + self._delay: OrnamentDelay|OffsetQL = 0.0 self.delay = delay # use property setter @property - def upperAccidental(self) -> pitch.Accidental | None: + def upperAccidental(self) -> pitch.Accidental|None: ''' This is the Turn's upperAccidental. Whether or not it is visible is dictated by the upperAccidental's displayStatus. @@ -1842,11 +1842,11 @@ def upperAccidental(self) -> pitch.Accidental | None: return self._upperAccidental @upperAccidental.setter - def upperAccidental(self, newUpperAccidental: pitch.Accidental | None): + def upperAccidental(self, newUpperAccidental: pitch.Accidental|None): self._upperAccidental = newUpperAccidental @property - def lowerAccidental(self) -> pitch.Accidental | None: + def lowerAccidental(self) -> pitch.Accidental|None: ''' This is the Turn's lowerAccidental. Whether or not it is visible is dictated by the upperAccidental's displayStatus. @@ -1854,11 +1854,11 @@ def lowerAccidental(self) -> pitch.Accidental | None: return self._lowerAccidental @lowerAccidental.setter - def lowerAccidental(self, newLowerAccidental: pitch.Accidental | None): + def lowerAccidental(self, newLowerAccidental: pitch.Accidental|None): self._lowerAccidental = newLowerAccidental @property - def delay(self) -> OrnamentDelay | OffsetQL: + def delay(self) -> OrnamentDelay|OffsetQL: ''' If delay is NO_DELAY, the turn is not delayed. @@ -1870,7 +1870,7 @@ def delay(self) -> OrnamentDelay | OffsetQL: return self._delay @delay.setter - def delay(self, newDelay: OrnamentDelay | OffsetQL): + def delay(self, newDelay: OrnamentDelay|OffsetQL): # we convert to OrnamentDelay if possible now, to simplify life later if isinstance(newDelay, (float, Fraction)) and newDelay <= 0: newDelay = OrnamentDelay.NO_DELAY @@ -1937,7 +1937,7 @@ def getSize( srcObj: note.GeneralNote, which: str, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, ) -> interval.IntervalBase: ''' Returns the size of one of the turn's two intervals (which='upper' @@ -1972,7 +1972,7 @@ def getSize( if ornamentalPitch.octave is None: ornamentalPitch.octave = ornamentalPitch.implicitOctave - accidental: pitch.Accidental | None = None + accidental: pitch.Accidental|None = None if which == 'upper': ornamentalPitch.transpose(interval.GenericInterval(2), inPlace=True) accidental = self.upperAccidental @@ -1992,7 +1992,7 @@ def resolveOrnamentalPitches( self, srcObj: note.GeneralNote, *, - keySig: key.KeySignature | None = None + keySig: key.KeySignature|None = None ): ''' Computes and stores the ornamental pitches for a Turn, given the srcObj @@ -2077,7 +2077,7 @@ def resolveOrnamentalPitches( self._ornamentalPitches = (upperPitch, lowerPitch) @property - def upperOrnamentalPitch(self) -> pitch.Pitch | None: + def upperOrnamentalPitch(self) -> pitch.Pitch|None: ''' Returns the turn's upper ornamental pitch. If resolveOrnamentalPitches has not yet been called, None is returned. @@ -2087,7 +2087,7 @@ def upperOrnamentalPitch(self) -> pitch.Pitch | None: return None @property - def lowerOrnamentalPitch(self) -> pitch.Pitch | None: + def lowerOrnamentalPitch(self) -> pitch.Pitch|None: ''' Returns the turn's lower ornamental pitch. If resolveOrnamentalPitches has not yet been called, None is returned. @@ -2108,10 +2108,10 @@ def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]: def updateAccidentalDisplay( self, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, @@ -2150,13 +2150,13 @@ def updateAccidentalDisplay( def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: # noinspection PyShadowingNames ''' realize a turn. @@ -2278,7 +2278,7 @@ def realize( remainderDuration = theDelay turnDuration = srcObj.duration.quarterLength - remainderDuration - fourthNoteQL: OffsetQL | None = None + fourthNoteQL: OffsetQL|None = None if turnDuration < 4 * self.quarterLength: if not self.autoScale: raise ExpressionException('The note is not long enough to realize a turn') @@ -2298,7 +2298,7 @@ def realize( # no need to check both intervals, they will both be perfectUnison, or neither will be. isTransposed: bool = not isUnison(firstTransposeInterval) - turnNotes: list[note.Note | note.Unpitched] = [] + turnNotes: list[note.Note|note.Unpitched] = [] firstNote = copy.deepcopy(srcObj) firstNote.expressions = [] @@ -2375,13 +2375,13 @@ def __init__(self, **keywords): def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: ''' realize an appoggiatura @@ -2525,13 +2525,13 @@ def numberOfMarks(self, num): def realize( self, - srcObj: note.Note | note.Unpitched, + srcObj: note.Note|note.Unpitched, *, - keySig: key.KeySignature | None = None, + keySig: key.KeySignature|None = None, inPlace: bool = False - ) -> tuple[list[note.Note | note.Unpitched], - note.Note | note.Unpitched | None, - list[note.Note | note.Unpitched]]: + ) -> tuple[list[note.Note|note.Unpitched], + note.Note|note.Unpitched|None, + list[note.Note|note.Unpitched]]: ''' Realize the ornament @@ -2737,7 +2737,7 @@ class ArpeggioMark(Expression): >>> am.type 'down' ''' - def __init__(self, arpeggioType: str | None = None, **keywords): + def __init__(self, arpeggioType: str|None = None, **keywords): super().__init__(**keywords) if not arpeggioType: arpeggioType = 'normal' @@ -2787,8 +2787,8 @@ def __init__(self, ) self.type = arpeggioType - def noteExtremes(self) -> tuple[note.Note | None, - note.Note | None]: + def noteExtremes(self) -> tuple[note.Note|None, + note.Note|None]: ''' Return the lowest and highest note spanned by the element, extracting them from Chords if need be. diff --git a/music21/features/base.py b/music21/features/base.py index e294807e7e..5b52d0512e 100644 --- a/music21/features/base.py +++ b/music21/features/base.py @@ -140,7 +140,7 @@ def __init__(self, **keywords ) -> None: self.stream = None # the original Stream, or None - self.data: DataInstance | None = None # a DataInstance object: use to get data + self.data: DataInstance|None = None # a DataInstance object: use to get data self.setData(dataOrStream) self.feature = None # Feature object that results from processing diff --git a/music21/features/native.py b/music21/features/native.py index 40fbec733c..04954b6c4a 100644 --- a/music21/features/native.py +++ b/music21/features/native.py @@ -114,7 +114,7 @@ def process(self) -> None: raise ValueError('Cannot process without a data instance or feature.') allKeys = self.data['flat.getElementsByClass(Key)'] - keyFeature: int | None = None + keyFeature: int|None = None if len(allKeys) == 1: k0 = allKeys[0] if k0.mode == 'major': diff --git a/music21/figuredBass/notation.py b/music21/figuredBass/notation.py index 2003a19403..f64a102374 100644 --- a/music21/figuredBass/notation.py +++ b/music21/figuredBass/notation.py @@ -209,10 +209,10 @@ def __init__(self, notationColumn: str = '') -> None: # Parse notation string self.notationColumn: str = notationColumn or '' self.figureStrings: list[str] = [] - self.origNumbers: tuple[int | None, ...] = () - self.origModStrings: tuple[str | None, ...] = () + self.origNumbers: tuple[int|None, ...] = () + self.origModStrings: tuple[str|None, ...] = () self.numbers: list[int] = [] - self.modifierStrings: tuple[str | None, ...] = () + self.modifierStrings: tuple[str|None, ...] = () self.extenders: list[bool] = [] self.hasExtenders: bool = False self._parseNotationColumn() @@ -513,13 +513,13 @@ class Figure(prebase.ProtoM21Object): def __init__( self, - number: int | None = 1, - modifierString: str | None = '', + number: int|None = 1, + modifierString: str|None = '', *, extender: bool = False ): - self.number: int | None = number - self.modifierString: str | None = modifierString + self.number: int|None = number + self.modifierString: str|None = modifierString self.modifier: Modifier = Modifier(modifierString) # look for extender's underscore self.hasExtender: bool = extender diff --git a/music21/figuredBass/resolution.py b/music21/figuredBass/resolution.py index 3c09a0aa51..64dd8ce901 100644 --- a/music21/figuredBass/resolution.py +++ b/music21/figuredBass/resolution.py @@ -746,7 +746,7 @@ def _resolvePitches(possibToResolve, howToResolve): def _unpackSeventhChord( seventhChord: chord.Chord -) -> list[pitch.Pitch | None]: +) -> list[pitch.Pitch|None]: ''' Takes in a Chord and returns a list of Pitches (or Nones) corresponding to the bass, root, fifth, seventh. diff --git a/music21/figuredBass/segment.py b/music21/figuredBass/segment.py index 235218f5b9..6c30b7da31 100644 --- a/music21/figuredBass/segment.py +++ b/music21/figuredBass/segment.py @@ -28,7 +28,7 @@ # used below _MOD = 'figuredBass.segment' -_defaultRealizerScale: dict[str, realizerScale.FiguredBassScale | None] = { +_defaultRealizerScale: dict[str, realizerScale.FiguredBassScale|None] = { 'scale': None, # singleton } @@ -65,12 +65,12 @@ class Segment: } def __init__(self, - bassNote: str | note.Note = 'C3', - notationString: str | None = None, - fbScale: realizerScale.FiguredBassScale | None = None, - fbRules: rules.Rules | None = None, + bassNote: str|note.Note = 'C3', + notationString: str|None = None, + fbScale: realizerScale.FiguredBassScale|None = None, + fbRules: rules.Rules|None = None, numParts=4, - maxPitch: str | pitch.Pitch = 'B5', + maxPitch: str|pitch.Pitch = 'B5', listOfPitches=None): ''' A Segment corresponds to a 1:1 realization of a bassNote and notationString @@ -862,8 +862,8 @@ def allSinglePossibilities(self): # HELPER METHODS # -------------- def getPitches(pitchNames=('C', 'E', 'G'), - bassPitch: str | pitch.Pitch = 'C3', - maxPitch: str | pitch.Pitch = 'C8'): + bassPitch: str|pitch.Pitch = 'C3', + maxPitch: str|pitch.Pitch = 'C8'): ''' Given a list of pitchNames, a bassPitch, and a maxPitch, returns a sorted list of pitches between the two limits (inclusive) which correspond to items in pitchNames. diff --git a/music21/freezeThaw.py b/music21/freezeThaw.py index 5701785f89..d1c00dc795 100644 --- a/music21/freezeThaw.py +++ b/music21/freezeThaw.py @@ -105,7 +105,7 @@ class StreamFreezeThawBase: def __init__(self): self.stream = None - def getPickleFp(self, directory: str | pathlib.Path) -> pathlib.Path: + def getPickleFp(self, directory: str|pathlib.Path) -> pathlib.Path: if not isinstance(directory, pathlib.Path): directory = pathlib.Path(directory) @@ -113,7 +113,7 @@ def getPickleFp(self, directory: str | pathlib.Path) -> pathlib.Path: streamStr = str(time.time()) return directory / ('m21-' + common.getMd5(streamStr) + '.p') - def getJsonFp(self, directory: str | pathlib.Path) -> pathlib.Path: + def getJsonFp(self, directory: str|pathlib.Path) -> pathlib.Path: return self.getPickleFp(directory).with_suffix('.p.json') diff --git a/music21/graph/__init__.py b/music21/graph/__init__.py index 3770679dfa..4e6877c5dc 100644 --- a/music21/graph/__init__.py +++ b/music21/graph/__init__.py @@ -66,7 +66,7 @@ def plotStream( streamObj: stream.Stream, - graphFormat: str | None = None, + graphFormat: str|None = None, xValue=None, yValue=None, zValue=None, diff --git a/music21/graph/findPlot.py b/music21/graph/findPlot.py index 51b83d61e4..8b5c5673d9 100644 --- a/music21/graph/findPlot.py +++ b/music21/graph/findPlot.py @@ -182,7 +182,7 @@ def getPlotClassesFromFormat(graphFormat, checkPlotClasses=None): return filteredPlots -def getAxisClassFromValue(axisValue: str) -> type[axis.Axis] | None: +def getAxisClassFromValue(axisValue: str) -> type[axis.Axis]|None: ''' given an axis value return the single best axis for the value, or None @@ -205,7 +205,7 @@ def getAxisClassFromValue(axisValue: str) -> type[axis.Axis] | None: return None -def axisMatchesValue(axisClass: type[axis.Axis] | axis.Axis, +def axisMatchesValue(axisClass: type[axis.Axis]|axis.Axis, axisValue: str) -> bool: ''' Returns Bool about whether axisValue.lower() is anywhere in axisClass.quantities @@ -237,7 +237,7 @@ def axisMatchesValue(axisClass: type[axis.Axis] | axis.Axis, return False -def getPlotsToMake(graphFormat: str | None = None, +def getPlotsToMake(graphFormat: str|None = None, xValue=None, yValue=None, zValue=None): diff --git a/music21/graph/plot.py b/music21/graph/plot.py index 2c659836ad..1fd1fbd41e 100644 --- a/music21/graph/plot.py +++ b/music21/graph/plot.py @@ -1051,7 +1051,7 @@ class HorizontalBar(primitives.GraphHorizontalBar, PlotStreamMixin): def __init__( self, - streamObj: stream.Stream | None = None, + streamObj: stream.Stream|None = None, *, colorByPart=False, **keywords diff --git a/music21/graph/primitives.py b/music21/graph/primitives.py index 2b5ee37d71..4956b489f6 100644 --- a/music21/graph/primitives.py +++ b/music21/graph/primitives.py @@ -98,7 +98,7 @@ class Graph(prebase.ProtoM21Object): ''' graphType = 'genericGraph' axisKeys: tuple[str, ...] = ('x', 'y') - figureSizeDefault: tuple[int | float, ...] = (6, 6) + figureSizeDefault: tuple[int|float, ...] = (6, 6) keywordConfigurables: tuple[str, ...] = ( 'alpha', @@ -1004,7 +1004,7 @@ def renderSubplot(self, subplot) -> None: if points: uniformFormatPerRow = (len(points[0]) == 2) - rowFaceColors: str | list[str] + rowFaceColors: str|list[str] if uniformFormatPerRow: rowFaceColors = faceColor positionPoints = points diff --git a/music21/harmony.py b/music21/harmony.py index 581ae7f233..b3ea94effc 100644 --- a/music21/harmony.py +++ b/music21/harmony.py @@ -210,10 +210,10 @@ class Harmony(chord.Chord): # INITIALIZER # def __init__(self, - figure: str | None = None, - root: str | pitch.Pitch | None = None, - bass: str | pitch.Pitch | None = None, - inversion: int | None = None, + figure: str|None = None, + root: str|pitch.Pitch|None = None, + bass: str|pitch.Pitch|None = None, + inversion: int|None = None, updatePitches: bool = True, **keywords ): @@ -276,7 +276,7 @@ def _updatePitches(self): ''' return - def _updateFromParameters(self, root, bass, inversion: int | None = None): + def _updateFromParameters(self, root, bass, inversion: int|None = None): ''' This method must be called twice, once before the pitches are rendered, and once after. This is because after the pitches @@ -602,9 +602,9 @@ class ChordStepModification(prebase.ProtoM21Object): # INITIALIZER # def __init__(self, modType=None, degree=None, intervalObj=None) -> None: - self._modType: str | None = None # add, alter, subtract + self._modType: str|None = None # add, alter, subtract self._interval: interval.Interval # alteration of degree, alter ints in mxl - self._degree: int | None = None # the degree number, where 3 is the third + self._degree: int|None = None # the degree number, where 3 is the third # use properties if defined: runs certain type conversions if modType is not None: self.modType = modType @@ -1608,9 +1608,9 @@ class ChordSymbol(Harmony): def __init__(self, figure=None, - root: pitch.Pitch | str | None = None, - bass: pitch.Pitch | str | None = None, - inversion: int | None = None, + root: pitch.Pitch|str|None = None, + bass: pitch.Pitch|str|None = None, + inversion: int|None = None, kind='', kindStr='', **keywords @@ -2378,7 +2378,7 @@ def inversionIsValid(self, inversion): else: return False - def transpose(self: T, value, *, inPlace=False) -> T | None: + def transpose(self: T, value, *, inPlace=False) -> T|None: ''' Overrides :meth:`~music21.chord.Chord.transpose` so that this ChordSymbol's `figure` is appropriately cleared afterward. @@ -2484,7 +2484,7 @@ def _parseFigure(self): # do nothing, everything is already set. return - def transpose(self: NCT, _value, *, inPlace=False) -> NCT | None: + def transpose(self: NCT, _value, *, inPlace=False) -> NCT|None: ''' Overrides :meth:`~music21.chord.Chord.transpose` to do nothing. diff --git a/music21/humdrum/spineParser.py b/music21/humdrum/spineParser.py index aca52efe7d..ca33c51226 100644 --- a/music21/humdrum/spineParser.py +++ b/music21/humdrum/spineParser.py @@ -790,11 +790,11 @@ class HumdrumFile(HumdrumDataCollection): as a mandatory argument a filename to be opened and read. ''' - def __init__(self, filename: str | pathlib.Path | None = None): + def __init__(self, filename: str|pathlib.Path|None = None): super().__init__() self.filename = filename - def parseFilename(self, filename: str | pathlib.Path | None = None): + def parseFilename(self, filename: str|pathlib.Path|None = None): if filename is None: filename = self.filename if filename is None: @@ -1066,7 +1066,7 @@ def __init__(self, spineId: int = 0, eventList=None, streamClass=stream.Stream): self._spineCollection = None self._spineType = None - self.isFirstVoice: bool | None = None + self.isFirstVoice: bool|None = None self.iterIndex = None def _reprInternal(self): @@ -1570,7 +1570,7 @@ def __init__(self, contents: str = '', position: int = 0): self.contents: str = contents self.position: int = position self.protoSpineId: int = 0 - self.spineId: int | None = None + self.spineId: int|None = None def _reprInternal(self): return self.contents @@ -2007,7 +2007,7 @@ def makeVoices(self) -> None: if not hasVoices: continue - voices: list[stream.Voice | None] = [None for i in range(10)] + voices: list[stream.Voice|None] = [None for i in range(10)] measureElements = el.elements for mEl in measureElements: mElGroups = mEl.groups diff --git a/music21/instrument.py b/music21/instrument.py index 29b7fa70d4..b368cb1b6a 100644 --- a/music21/instrument.py +++ b/music21/instrument.py @@ -46,7 +46,7 @@ def unbundleInstruments(streamIn: stream.Stream, *, - inPlace=False) -> stream.Stream | None: + inPlace=False) -> stream.Stream|None: # noinspection PyShadowingNames ''' takes a :class:`~music21.stream.Stream` that has :class:`~music21.note.NotRest` objects @@ -85,7 +85,7 @@ def unbundleInstruments(streamIn: stream.Stream, def bundleInstruments(streamIn: stream.Stream, *, - inPlace=False) -> stream.Stream | None: + inPlace=False) -> stream.Stream|None: # noinspection PyShadowingNames ''' >>> up1 = note.Unpitched() @@ -150,32 +150,32 @@ class Instrument(base.Music21Object): ''' classSortOrder = -25 - def __init__(self, instrumentName: str | None = None, **keywords): + def __init__(self, instrumentName: str|None = None, **keywords): super().__init__(**keywords) - self.partId: str | None = None + self.partId: str|None = None self._partIdIsRandom = False - self.partName: str | None = None - self.partAbbreviation: str | None = None + self.partName: str|None = None + self.partAbbreviation: str|None = None - self.printPartName: bool | None = None # True = yes, False = no, None = let others decide - self.printPartAbbreviation: bool | None = None + self.printPartName: bool|None = None # True = yes, False = no, None = let others decide + self.printPartAbbreviation: bool|None = None - self.instrumentId: str | None = None # apply to midi and instrument + self.instrumentId: str|None = None # apply to midi and instrument self._instrumentIdIsRandom = False - self.instrumentName: str | None = instrumentName - self.instrumentAbbreviation: str | None = None - self.midiProgram: int | None = None # 0-indexed - self.midiChannel: int | None = None # 0-indexed - self.instrumentSound: str | None = None + self.instrumentName: str|None = instrumentName + self.instrumentAbbreviation: str|None = None + self.midiProgram: int|None = None # 0-indexed + self.midiChannel: int|None = None # 0-indexed + self.instrumentSound: str|None = None - self.lowestNote: pitch.Pitch | None = None - self.highestNote: pitch.Pitch | None = None + self.lowestNote: pitch.Pitch|None = None + self.highestNote: pitch.Pitch|None = None # define interval to go from written to sounding - self.transposition: interval.Interval | None = None + self.transposition: interval.Interval|None = None self.inGMPercMap = False self.soundfontFn = None # if defined... diff --git a/music21/interval.py b/music21/interval.py index e01185b892..c4f77a5a60 100644 --- a/music21/interval.py +++ b/music21/interval.py @@ -313,7 +313,7 @@ class IntervalException(exceptions21.Music21Exception): # some utility functions def _extractPitch( - nOrP: note.Note | pitch.Pitch + nOrP: note.Note|pitch.Pitch ) -> pitch.Pitch: ''' utility function to return either the object itself @@ -412,7 +412,7 @@ def convertDiatonicNumberToStep(dn: int) -> tuple[StepName, int]: stepNumber = (dn - 1) - (octave * 7) return STEPNAMES[stepNumber], (octave - 1) -def parseSpecifier(value: str | int | Specifier) -> Specifier: +def parseSpecifier(value: str|int|Specifier) -> Specifier: ''' Given an integer or a string representing a "specifier" (major, minor, perfect, diminished, etc.), return the Specifier. @@ -485,7 +485,7 @@ def parseSpecifier(value: str | int | Specifier) -> Specifier: raise IntervalException(f'Cannot find a match for value: {value!r}') -def convertGeneric(value: int | str) -> int: +def convertGeneric(value: int|str) -> int: ''' Convert an interval specified in terms of its name (second, third) into an integer. If integers are passed, assume the are correct. @@ -550,7 +550,7 @@ def convertGeneric(value: int | str) -> int: def convertSemitoneToSpecifierGenericMicrotone( - count: int | float + count: int|float ) -> tuple[Specifier, int, float]: ''' Given a number of semitones (positive or negative), @@ -602,7 +602,7 @@ def convertSemitoneToSpecifierGenericMicrotone( return (spec, (generic + (octave * 7)) * dirScale, cents) -def convertSemitoneToSpecifierGeneric(count: int | float) -> tuple[Specifier, int]: +def convertSemitoneToSpecifierGeneric(count: int|float) -> tuple[Specifier, int]: ''' Given a number of semitones, return a default diatonic specifier, and a number that can be used as a GenericInterval @@ -885,7 +885,7 @@ class GenericInterval(IntervalBase): * Changed in v6: large intervals get abbreviations ''' def __init__(self, - value: int | str = 'Unison', + value: int|str = 'Unison', **keywords): super().__init__(**keywords) self._value: int = 1 @@ -1425,7 +1425,7 @@ def transposePitch(self, p: pitch.Pitch, *, inPlace=False): def transposePitchKeyAware( self, p: pitch.Pitch, - k: key.KeySignature | None = None, + k: key.KeySignature|None = None, *, inPlace: bool = False ): @@ -1522,7 +1522,7 @@ def transposePitchKeyAware( if inPlace is False: return newPitch - def getDiatonic(self, specifier: Specifier | str) -> DiatonicInterval: + def getDiatonic(self, specifier: Specifier|str) -> DiatonicInterval: ''' Given a specifier, return a :class:`~music21.interval.DiatonicInterval` object. @@ -1668,8 +1668,8 @@ class DiatonicInterval(IntervalBase): } def __init__(self, - specifier: str | int = 'P', - generic: int | GenericInterval | str = 1, + specifier: str|int = 'P', + generic: int|GenericInterval|str = 1, **keywords): super().__init__(**keywords) @@ -2224,13 +2224,13 @@ class ChromaticInterval(IntervalBase): True ''' - def __init__(self, semitones: int | float = 0, **keywords): + def __init__(self, semitones: int|float = 0, **keywords): super().__init__(**keywords) if semitones == int(semitones): semitones = int(semitones) - self.semitones: int | float = semitones + self.semitones: int|float = semitones def _reprInternal(self) -> str: return str(self.directed) @@ -2284,7 +2284,7 @@ def cents(self) -> float: return round(self.semitones * 100.0, 5) @property - def directed(self) -> int | float: + def directed(self) -> int|float: ''' A synonym for `.semitones` @@ -2295,7 +2295,7 @@ def directed(self) -> int | float: return self.semitones @property - def undirected(self) -> int | float: + def undirected(self) -> int|float: ''' The absolute value of the number of semitones: @@ -2326,7 +2326,7 @@ def direction(self) -> Direction: return Direction.OBLIQUE @property - def mod12(self) -> int | float: + def mod12(self) -> int|float: ''' The number of semitones within an octave using modulo arithmatic. @@ -2344,7 +2344,7 @@ def mod12(self) -> int | float: return self.semitones % 12 @property - def simpleUndirected(self) -> int | float: + def simpleUndirected(self) -> int|float: ''' The number of semitones within an octave while ignoring direction. @@ -2362,7 +2362,7 @@ def simpleUndirected(self) -> int | float: return self.undirected % 12 @property - def simpleDirected(self) -> int | float: + def simpleDirected(self) -> int|float: ''' The number of semitones within an octave while preserving direction. @@ -2601,8 +2601,8 @@ def _stringToDiatonicChromatic( def notesToGeneric( - n1: pitch.Pitch | note.Note, - n2: pitch.Pitch | note.Note + n1: pitch.Pitch|note.Note, + n2: pitch.Pitch|note.Note ) -> GenericInterval: ''' Given two :class:`~music21.note.Note` objects, @@ -2629,8 +2629,8 @@ def notesToGeneric( return GenericInterval(genDist) def notesToChromatic( - n1: pitch.Pitch | note.Note, - n2: pitch.Pitch | note.Note + n1: pitch.Pitch|note.Note, + n2: pitch.Pitch|note.Note ) -> ChromaticInterval: ''' Given two :class:`~music21.note.Note` objects, @@ -2739,8 +2739,8 @@ def intervalsToDiatonic( def intervalFromGenericAndChromatic( - gInt: GenericInterval | int, - cInt: ChromaticInterval | int | float, + gInt: GenericInterval|int, + cInt: ChromaticInterval|int|float, ) -> Interval: ''' Given a :class:`~music21.interval.GenericInterval` and a @@ -2995,16 +2995,16 @@ def __init__(self, pitch.Pitch, note.Note, None] = None, - arg1: pitch.Pitch | note.Note | None = None, + arg1: pitch.Pitch|note.Note|None = None, /, *, - diatonic: DiatonicInterval | None = None, - chromatic: ChromaticInterval | None = None, - pitchStart: pitch.Pitch | None = None, - pitchEnd: pitch.Pitch | None = None, - noteStart: note.Note | pitch.Pitch | None = None, - noteEnd: note.Note | pitch.Pitch | None = None, - name: str | None = None, + diatonic: DiatonicInterval|None = None, + chromatic: ChromaticInterval|None = None, + pitchStart: pitch.Pitch|None = None, + pitchEnd: pitch.Pitch|None = None, + noteStart: note.Note|pitch.Pitch|None = None, + noteEnd: note.Note|pitch.Pitch|None = None, + name: str|None = None, **keywords): super().__init__(**keywords) @@ -3080,8 +3080,8 @@ def __init__(self, self.chromatic: ChromaticInterval = chromatic # these can be accessed through pitchStart and pitchEnd properties - self._pitchStart: pitch.Pitch | None = pitchStart - self._pitchEnd: pitch.Pitch | None = pitchEnd + self._pitchStart: pitch.Pitch|None = pitchStart + self._pitchEnd: pitch.Pitch|None = pitchEnd self.intervalType: t.Literal['harmonic', 'melodic', ''] = '' @@ -3202,15 +3202,15 @@ def directedSimpleNiceName(self) -> str: return self.diatonic.directedSimpleNiceName @property - def semitones(self) -> int | float: + def semitones(self) -> int|float: return self.chromatic.semitones @property - def direction(self) -> Direction | None: + def direction(self) -> Direction|None: return self.chromatic.direction @property - def specifier(self) -> Specifier | None: + def specifier(self) -> Specifier|None: return self.diatonic.specifier @property @@ -3335,7 +3335,7 @@ def transposePitch(self, p: pitch.Pitch, *, reverse=False, - maxAccidental: int | None = 4, + maxAccidental: int|None = 4, inPlace=False): ''' Given a :class:`~music21.pitch.Pitch` object, return a new, @@ -3668,7 +3668,7 @@ def pitchEnd(self, p: music21.pitch.Pitch): self._pitchStart = pitch1 @property - def noteStart(self) -> music21.note.Note | None: + def noteStart(self) -> music21.note.Note|None: ''' Return or set the Note that pitchStart is attached to. For backwards compatibility @@ -3681,14 +3681,14 @@ def noteStart(self) -> music21.note.Note | None: return note.Note(pitch=p) @noteStart.setter - def noteStart(self, n: music21.note.Note | None): + def noteStart(self, n: music21.note.Note|None): if n: self.pitchStart = n.pitch else: self.pitchStart = None @property - def noteEnd(self) -> music21.note.Note | None: + def noteEnd(self) -> music21.note.Note|None: ''' Return or set the Note that pitchEnd is attached to. For backwards compatibility @@ -3701,7 +3701,7 @@ def noteEnd(self) -> music21.note.Note | None: return note.Note(pitch=p) @noteEnd.setter - def noteEnd(self, n: music21.note.Note | None): + def noteEnd(self, n: music21.note.Note|None): if n: self.pitchEnd = n.pitch else: @@ -3709,9 +3709,9 @@ def noteEnd(self, n: music21.note.Note | None): # ------------------------------------------------------------------------------ -def getWrittenHigherNote(note1: note.Note | pitch.Pitch, - note2: note.Note | pitch.Pitch - ) -> note.Note | pitch.Pitch: +def getWrittenHigherNote(note1: note.Note|pitch.Pitch, + note2: note.Note|pitch.Pitch + ) -> note.Note|pitch.Pitch: ''' Given two :class:`~music21.pitch.Pitch` or :class:`~music21.note.Note` objects, this function returns the higher element based on diatonic note @@ -3747,9 +3747,9 @@ def getWrittenHigherNote(note1: note.Note | pitch.Pitch, return getAbsoluteHigherNote(note1, note2) -def getAbsoluteHigherNote(note1: note.Note | pitch.Pitch, - note2: note.Note | pitch.Pitch - ) -> note.Note | pitch.Pitch: +def getAbsoluteHigherNote(note1: note.Note|pitch.Pitch, + note2: note.Note|pitch.Pitch + ) -> note.Note|pitch.Pitch: ''' Given two :class:`~music21.pitch.Pitch` or :class:`~music21.note.Note` objects, returns the higher element based on sounding pitch. @@ -3770,9 +3770,9 @@ def getAbsoluteHigherNote(note1: note.Note | pitch.Pitch, return note1 -def getWrittenLowerNote(note1: note.Note | pitch.Pitch, - note2: note.Note | pitch.Pitch - ) -> note.Note | pitch.Pitch: +def getWrittenLowerNote(note1: note.Note|pitch.Pitch, + note2: note.Note|pitch.Pitch + ) -> note.Note|pitch.Pitch: ''' Given two :class:`~music21.pitch.Pitch` or :class:`~music21.note.Note` objects, returns the lower element based on diatonic note @@ -3802,9 +3802,9 @@ def getWrittenLowerNote(note1: note.Note | pitch.Pitch, return getAbsoluteLowerNote(note1, note2) -def getAbsoluteLowerNote(note1: note.Note | pitch.Pitch, - note2: note.Note | pitch.Pitch - ) -> note.Note | pitch.Pitch: +def getAbsoluteLowerNote(note1: note.Note|pitch.Pitch, + note2: note.Note|pitch.Pitch + ) -> note.Note|pitch.Pitch: ''' Given two :class:`~music21.note.Note` or :class:`~music21.pitch.Pitch` objects, returns the lower element based on actual pitch. @@ -3827,7 +3827,7 @@ def getAbsoluteLowerNote(note1: note.Note | pitch.Pitch, def transposePitch( pitch1: pitch.Pitch, - interval1: str | Interval, + interval1: str|interval, *, inPlace=False ) -> pitch.Pitch: @@ -3880,7 +3880,7 @@ def transposePitch( def transposeNote( note1: note.Note, - intervalString: str | Interval) -> note.Note: + intervalString: str|interval) -> note.Note: ''' To be deprecated: call `n.transpose(intervalString)` directly. diff --git a/music21/key.py b/music21/key.py index 1590194ae4..b8c612ff04 100644 --- a/music21/key.py +++ b/music21/key.py @@ -41,7 +41,7 @@ KeySignatureType = t.TypeVar('KeySignatureType', bound='KeySignature') KeyType = t.TypeVar('KeyType', bound='Key') -TransposeTypes = int | str | interval.Interval | interval.GenericInterval +TransposeTypes = int|str|interval.Interval|interval.GenericInterval # ------------------------------------------------------------------------------ @@ -167,8 +167,8 @@ def sharpsToPitch(sharpCount): } -def pitchToSharps(value: str | pitch.Pitch | note.Note, - mode: str | None = None) -> int: +def pitchToSharps(value: str|pitch.Pitch|note.Note, + mode: str|None = None) -> int: ''' Given a pitch string or :class:`music21.pitch.Pitch` or :class:`music21.note.Note` object, @@ -356,7 +356,7 @@ class KeySignature(base.Music21Object): classSortOrder = 2 - def __init__(self, sharps: int | None = 0, **keywords): + def __init__(self, sharps: int|None = 0, **keywords): super().__init__(**keywords) # position on the circle of fifths, where 1 is one sharp, -1 is one flat @@ -374,7 +374,7 @@ def __init__(self, sharps: int | None = 0, **keywords): self._sharps = sharps # need to store a list of pitch objects, used for creating a # non-traditional key - self._alteredPitches: list[pitch.Pitch] | None = None + self._alteredPitches: list[pitch.Pitch]|None = None self.accidentalsApplyOnlyToOctave = False # -------------------------------------------------------------------------- @@ -399,7 +399,7 @@ def _strDescription(self): def _reprInternal(self): return 'of ' + self._strDescription() - def asKey(self, mode: str | None = None, tonic: str | None = None): + def asKey(self, mode: str|None = None, tonic: str|None = None): ''' Return a `key.Key` object representing this KeySignature object as a key in the given mode or in the given tonic. If `mode` is None, and `tonic` is not provided, @@ -540,7 +540,7 @@ def alteredPitches(self) -> list[pitch.Pitch]: return post @alteredPitches.setter - def alteredPitches(self, newAlteredPitches: list[str | pitch.Pitch | note.Note] + def alteredPitches(self, newAlteredPitches: list[str|pitch.Pitch|note.Note] ) -> None: self.clearCache() newList: list[pitch.Pitch] = [] @@ -578,7 +578,7 @@ def isNonTraditional(self) -> bool: else: return False - def accidentalByStep(self, step: StepName) -> pitch.Accidental | None: + def accidentalByStep(self, step: StepName) -> pitch.Accidental|None: ''' Given a step (C, D, E, F, etc.) return the accidental for that note in this key (using the natural minor for minor) @@ -677,7 +677,7 @@ def transpose(self: KeySignatureType, def transpose(self: KeySignatureType, value: TransposeTypes, *, - inPlace: bool = False) -> KeySignatureType | None: + inPlace: bool = False) -> KeySignatureType|None: ''' Transpose the KeySignature by the user-provided value. If the value is an integer, the transposition is treated @@ -724,7 +724,7 @@ def transpose(self: KeySignatureType, >>> eFlat ''' - intervalObj: interval.Interval | interval.GenericInterval + intervalObj: interval.Interval|interval.GenericInterval if isinstance(value, interval.Interval): # it is an Interval class intervalObj = value elif isinstance(value, interval.GenericInterval): @@ -752,7 +752,7 @@ def transpose(self: KeySignatureType, else: return None - def transposePitchFromC(self, p: pitch.Pitch, *, inPlace=False) -> pitch.Pitch | None: + def transposePitchFromC(self, p: pitch.Pitch, *, inPlace=False) -> pitch.Pitch|None: ''' Takes a pitch in C major and transposes it so that it has the same step position in the current key signature. @@ -848,10 +848,10 @@ def getScale(self, mode='major'): # -------------------------------------------------------------------------- # properties - def _getSharps(self) -> int | None: + def _getSharps(self) -> int|None: return self._sharps - def _setSharps(self, value: int | None): + def _setSharps(self, value: int|None): if value != self._sharps: self._sharps = value self.clearCache() @@ -951,11 +951,11 @@ class Key(KeySignature, scale.DiatonicScale): * Changed in v8: keys now compare equal regardless of the octave of their tonics. ''' _sharps = 0 - _mode: str | None = None + _mode: str|None = None tonic: pitch.Pitch def __init__(self, - tonic: str | pitch.Pitch | note.Note = 'C', + tonic: str|pitch.Pitch|note.Note = 'C', mode=None, **keywords): if isinstance(tonic, (note.Note, pitch.Pitch)): @@ -1251,7 +1251,7 @@ def transpose(self: KeyType, value: TransposeTypes, *, inPlace: bool = False - ) -> KeyType | None: + ) -> KeyType|None: ''' Transpose the Key by the user-provided value. If the value is an integer, the transposition is treated diff --git a/music21/layout.py b/music21/layout.py index 977b65435b..d5a4591980 100644 --- a/music21/layout.py +++ b/music21/layout.py @@ -155,20 +155,20 @@ class ScoreLayout(LayoutBase): def __init__(self, *, - scalingMillimeters: int | float | None = None, - scalingTenths: int | float | None = None, - musicFont: str | None = None, - wordFont: str | None = None, - pageLayout: PageLayout | None = None, - systemLayout: SystemLayout | None = None, - staffLayoutList: list[StaffLayout] | None = None, + scalingMillimeters: int|float|None = None, + scalingTenths: int|float|None = None, + musicFont: str|None = None, + wordFont: str|None = None, + pageLayout: PageLayout|None = None, + systemLayout: SystemLayout|None = None, + staffLayoutList: list[StaffLayout]|None = None, **keywords): super().__init__(**keywords) self.scalingMillimeters = scalingMillimeters self.scalingTenths = scalingTenths - self.pageLayout: PageLayout | None = pageLayout - self.systemLayout: SystemLayout | None = systemLayout + self.pageLayout: PageLayout|None = pageLayout + self.systemLayout: SystemLayout|None = systemLayout self.staffLayoutList: list[StaffLayout] = [] self.musicFont = musicFont self.wordFont = wordFont @@ -226,14 +226,14 @@ class PageLayout(LayoutBase): def __init__(self, *, - pageNumber: int | None = None, - leftMargin: int | float | None = None, - rightMargin: int | float | None = None, - topMargin: int | float | None = None, - bottomMargin: int | float | None = None, - pageHeight: int | float | None = None, - pageWidth: int | float | None = None, - isNew: bool | None = None, + pageNumber: int|None = None, + leftMargin: int|float|None = None, + rightMargin: int|float|None = None, + topMargin: int|float|None = None, + bottomMargin: int|float|None = None, + pageHeight: int|float|None = None, + pageWidth: int|float|None = None, + isNew: bool|None = None, **keywords): super().__init__(**keywords) @@ -275,11 +275,11 @@ class SystemLayout(LayoutBase): ''' def __init__(self, *, - leftMargin: int | float | None = None, - rightMargin: int | float | None = None, - distance: int | float | None = None, - topDistance: int | float | None = None, - isNew: bool | None = None, + leftMargin: int|float|None = None, + rightMargin: int|float|None = None, + distance: int|float|None = None, + topDistance: int|float|None = None, + isNew: bool|None = None, **keywords): super().__init__(**keywords) @@ -360,11 +360,11 @@ class StaffLayout(LayoutBase): } def __init__(self, *, - distance: int | float | None = None, - staffNumber: int | float | None = None, - staffSize: int | float | None = None, - staffLines: int | None = None, - hidden: bool | None = None, + distance: int|float|None = None, + staffNumber: int|float|None = None, + staffSize: int|float|None = None, + staffLines: int|None = None, + hidden: bool|None = None, staffType: StaffType = StaffType.REGULAR, **keywords): super().__init__(**keywords) @@ -372,7 +372,7 @@ def __init__(self, # this is the distance between adjacent staves self.distance = distance self.staffNumber = staffNumber - self.staffSize: float | None = None if staffSize is None else float(staffSize) + self.staffSize: float|None = None if staffSize is None else float(staffSize) self.staffLines = staffLines self.hidden = hidden # True = hidden; False = shown; None = inherit self.staffType: StaffType = staffType @@ -427,16 +427,16 @@ class StaffGroup(spanner.Spanner): ''' def __init__(self, *spannedElements, - name: str | None = None, + name: str|None = None, barTogether: t.Literal[True, False, None, 'Mensurstrich'] = True, - abbreviation: str | None = None, - symbol: t.Literal['bracket', 'line', 'brace', 'square'] | None = None, + abbreviation: str|None = None, + symbol: t.Literal['bracket', 'line', 'brace', 'square']|None = None, **keywords): super().__init__(*spannedElements, **keywords) self.name = name or abbreviation # if this group has a name self.abbreviation = abbreviation - self._symbol: t.Literal['bracket', 'line', 'brace', 'square'] | None = None + self._symbol: t.Literal['bracket', 'line', 'brace', 'square']|None = None self.symbol = symbol # determines if barlines are grouped through; this is group barline # in musicxml @@ -475,10 +475,10 @@ def _setBarTogether(self, value: t.Literal[True, False, None, 'Mensurstrich', 'y 'Mensurstrich' ''') - def _getSymbol(self) -> t.Literal['bracket', 'line', 'brace', 'square'] | None: + def _getSymbol(self) -> t.Literal['bracket', 'line', 'brace', 'square']|None: return self._symbol - def _setSymbol(self, value: t.Literal['bracket', 'line', 'brace', 'square'] | None): + def _setSymbol(self, value: t.Literal['bracket', 'line', 'brace', 'square']|None): if value is None or str(value).lower() == 'none': self._symbol = None elif value.lower() in ['brace', 'line', 'bracket', 'square']: @@ -1294,7 +1294,7 @@ def getSystemBeforeThis( self, pageId: int, systemId: int - ) -> tuple[int | None, int]: + ) -> tuple[int|None, int]: # noinspection PyShadowingNames ''' given a pageId and systemId, get the (pageId, systemId) for the previous system. diff --git a/music21/lily/lilyObjects.py b/music21/lily/lilyObjects.py index 58514dc32f..3eb5f22769 100644 --- a/music21/lily/lilyObjects.py +++ b/music21/lily/lilyObjects.py @@ -1567,7 +1567,7 @@ class LyEventChord(LyObject): | CHORD_REPETITION optional_notemode_duration post_events | MULTI_MEASURE_REST optional_notemode_duration post_events | command_element - | note_chord_element + |note_chord_element simple_chord_elements can be a LySimpleElement object. Or it can be a LyNewChord or LyFigureSpec + Duration diff --git a/music21/lily/translate.py b/music21/lily/translate.py index 44c9971b65..0ee150a8a6 100644 --- a/music21/lily/translate.py +++ b/music21/lily/translate.py @@ -1527,7 +1527,7 @@ def octaveCharactersFromPitch(self, pitch): def lyMultipliedDurationFromDuration( self, - durationObj: duration.Duration | duration.DurationTuple, + durationObj: duration.Duration|duration.DurationTuple, ): r''' take a simple Duration (that is, one with one DurationTuple) @@ -1567,7 +1567,7 @@ def lyMultipliedDurationFromDuration( >>> [str(lpc.lyMultipliedDurationFromDuration(c)) for c in components] ['1 ', '4 '] ''' - number_type: float | int | str + number_type: float|int|str try: number_type = duration.convertTypeToNumber(durationObj.type) # module call except duration.DurationException as de: diff --git a/music21/mei/base.py b/music21/mei/base.py index 725127e1c6..161d46dcf4 100644 --- a/music21/mei/base.py +++ b/music21/mei/base.py @@ -353,8 +353,8 @@ def run(self) -> stream.Stream: # ----------------------------------------------------------------------------- def safePitch( name: str, - accidental: str | None = None, - octave: str | int = '' + accidental: str|None = None, + octave: str|int = '' ) -> pitch.Pitch: ''' Safely build a :class:`~music21.pitch.Pitch` from a string. @@ -392,7 +392,7 @@ def safePitch( def makeDuration( - base: float | int | Fraction = 0.0, + base: float|int|Fraction = 0.0, dots: int = 0 ) -> duration.Duration: ''' @@ -628,7 +628,7 @@ def _makeArticList(attr): return articList -def _getOctaveShift(dis: t.Literal['8', '15', '22'] | None, +def _getOctaveShift(dis: t.Literal['8', '15', '22']|None, disPlace: str) -> int: ''' Use :func:`_getOctaveShift` to calculate the :attr:`octaveShift` attribute for a @@ -1038,7 +1038,7 @@ def _timeSigFromAttrs(elem): return meter.TimeSignature(f"{elem.get('meter.count')!s}/{elem.get('meter.unit')!s}") -def _keySigFromAttrs(elem: Element) -> key.Key | key.KeySignature: +def _keySigFromAttrs(elem: Element) -> key.Key|key.KeySignature: ''' From any tag with (at minimum) either @key.pname or @key.sig attributes, make a :class:`KeySignature` or :class:`Key`, as possible. diff --git a/music21/metadata/__init__.py b/music21/metadata/__init__.py index 142b6d9ad9..ecdd633bf4 100755 --- a/music21/metadata/__init__.py +++ b/music21/metadata/__init__.py @@ -264,7 +264,7 @@ def __init__(self, **keywords) -> None: def add(self, name: str, - value: t.Any | Iterable[t.Any], + value: t.Any|Iterable[t.Any], ) -> None: ''' Adds a single item or multiple items with this name, leaving any existing @@ -330,7 +330,7 @@ def getCustom(self, name: str) -> tuple[ValueType, ...]: ''' return self._get(name, isCustom=True) - def addCustom(self, name: str, value: t.Any | Iterable[t.Any]): + def addCustom(self, name: str, value: t.Any|Iterable[t.Any]): ''' Adds any custom-named metadata items. The name can be free-form, or it can be a custom 'namespace:name'. @@ -359,7 +359,7 @@ def addCustom(self, name: str, value: t.Any | Iterable[t.Any]): ''' self._add(name, value, isCustom=True) - def setCustom(self, name: str, value: t.Any | Iterable[t.Any]): + def setCustom(self, name: str, value: t.Any|Iterable[t.Any]): ''' Sets any custom-named metadata items (deleting any existing such items). The name can be free-form, or it can be a custom 'namespace:name'. @@ -391,7 +391,7 @@ def setCustom(self, name: str, value: t.Any | Iterable[t.Any]): # A few utility routines for clients calling public APIs @staticmethod - def uniqueNameToNamespaceName(uniqueName: str) -> str | None: + def uniqueNameToNamespaceName(uniqueName: str) -> str|None: ''' Translates a unique name to the associated standard property's namespace name (i.e. the property's name in the form 'namespace:name'). @@ -417,7 +417,7 @@ def uniqueNameToNamespaceName(uniqueName: str) -> str | None: return properties.UNIQUE_NAME_TO_NAMESPACE_NAME.get(uniqueName, None) @staticmethod - def namespaceNameToUniqueName(namespaceName: str) -> str | None: + def namespaceNameToUniqueName(namespaceName: str) -> str|None: ''' Translates a standard property namespace name ('namespace:name') to that standard property's uniqueName. @@ -442,7 +442,7 @@ def namespaceNameToUniqueName(namespaceName: str) -> str | None: return properties.NAMESPACE_NAME_TO_UNIQUE_NAME.get(namespaceName, None) @staticmethod - def isContributorUniqueName(uniqueName: str | None) -> bool: + def isContributorUniqueName(uniqueName: str|None) -> bool: ''' Determines if a unique name is associated with a standard contributor property. Returns False if no such associated standard contributor @@ -471,7 +471,7 @@ def isContributorUniqueName(uniqueName: str | None) -> bool: ''' if not uniqueName: return False - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.UNIQUE_NAME_TO_PROPERTY_DESCRIPTION.get(uniqueName, None) ) if prop is None: @@ -878,7 +878,7 @@ def __getitem__(self, def __getitem__(self, key: str) -> tuple[Text, ...]: pass - def __getitem__(self, key: str) -> tuple[ValueType, ...] | tuple[Text, ...]: + def __getitem__(self, key: str) -> tuple[ValueType, ...]|tuple[Text, ...]: ''' "Dictionary key" access for all standard uniqueNames and standard keys of the form 'namespace:name'. @@ -925,7 +925,7 @@ def __getitem__(self, key: str) -> tuple[ValueType, ...] | tuple[Text, ...]: return self._get(key, isCustom=False) - def __setitem__(self, key: str, value: t.Any | Iterable[t.Any]): + def __setitem__(self, key: str, value: t.Any|Iterable[t.Any]): ''' "Dictionary key" access for all standard uniqueNames and standard keys of the form 'namespace:name'. @@ -996,7 +996,7 @@ def addContributor(self, c: Contributor): uniqueName: str = self._contributorRoleToUniqueName(c.role) self._add(uniqueName, c, isCustom=False) - def getContributorsByRole(self, role: str | None) -> tuple[Contributor, ...]: + def getContributorsByRole(self, role: str|None) -> tuple[Contributor, ...]: r''' Return a :class:`~music21.metadata.Contributor` if defined for a provided role. @@ -1043,10 +1043,10 @@ def getContributorsByRole(self, role: str | None) -> tuple[Contributor, ...]: def search( self, - query: str | t.Pattern | t.Callable[[str], bool] | None = None, - field: str | None = None, + query: str|t.Pattern|t.Callable[[str], bool]|None = None, + field: str|None = None, **keywords - ) -> tuple[bool, str | None]: + ) -> tuple[bool, str|None]: r''' Search one or all fields with a query, given either as a string or a regular expression match. @@ -1112,7 +1112,7 @@ def search( # TODO: Change to a namedtuple and add as a third element # during a successful search, the full value of the retrieved # field (so that 'Joplin' would return 'Joplin, Scott') - reQuery: t.Pattern | None = None + reQuery: t.Pattern|None = None valueFieldPairs = [] if query is None and field is None and not keywords: return (False, None) @@ -1145,7 +1145,7 @@ def search( # see if there is an associated grandfathered workId, and if so, # search for that, too. - workId: str | None = properties.UNIQUE_NAME_TO_MUSIC21_WORK_ID.get( + workId: str|None = properties.UNIQUE_NAME_TO_MUSIC21_WORK_ID.get( uniqueName, None ) @@ -1381,7 +1381,7 @@ def dateCreated(self, value: str) -> None: setattr(self, 'dateCreated', value) @property - def fileFormat(self) -> str | None: + def fileFormat(self) -> str|None: ''' Get or set the file format that was parsed. ''' @@ -1395,7 +1395,7 @@ def fileFormat(self, value: str) -> None: setattr(self, 'fileFormat', value) @property - def filePath(self) -> str | None: + def filePath(self) -> str|None: ''' Get or set the file path that was parsed. ''' @@ -1409,7 +1409,7 @@ def filePath(self, value: str) -> None: setattr(self, 'filePath', value) @property - def corpusFilePath(self) -> str | None: + def corpusFilePath(self) -> str|None: ''' Get or set the path within the corpus that was parsed. ''' @@ -1423,7 +1423,7 @@ def corpusFilePath(self, value: str) -> None: setattr(self, 'corpusFilePath', value) @property - def fileNumber(self) -> str | None: + def fileNumber(self) -> str|None: ''' Get or set the file number that was parsed. ''' @@ -1570,7 +1570,7 @@ def movementName(self, value: str) -> None: setattr(self, 'movementName', value) @property - def movementNumber(self) -> str | None: + def movementNumber(self) -> str|None: r''' Get or set the movement number as a string (or None) @@ -1593,7 +1593,7 @@ def movementNumber(self, value: str) -> None: setattr(self, 'movementNumber', value) @property - def number(self) -> str | None: + def number(self) -> str|None: r''' Get or set the number of the work within a collection of pieces, as a string. (for instance, the number within a collection of ABC files) @@ -1623,7 +1623,7 @@ def number(self, value: str) -> None: setattr(self, 'number', value) @property - def opusNumber(self) -> str | None: + def opusNumber(self) -> str|None: r''' Get or set the opus number. @@ -1675,7 +1675,7 @@ def title(self, value: str) -> None: setattr(self, 'title', value) @property - def bestTitle(self) -> str | None: + def bestTitle(self) -> str|None: r''' Get the title of the work, or the next-matched title string available from a related parameter fields. @@ -1717,7 +1717,7 @@ def bestTitle(self) -> str | None: 'movementName', ) for uniqueName in searchId: - titleSummary: str | None = self._getStringValueByNamespaceName( + titleSummary: str|None = self._getStringValueByNamespaceName( properties.UNIQUE_NAME_TO_NAMESPACE_NAME[uniqueName] ) if titleSummary: @@ -1728,7 +1728,7 @@ def bestTitle(self) -> str | None: # ----------------------------------------------------------------------------- # Internal support routines (many of them static). - def _getStringValueByNamespaceName(self, namespaceName: str) -> str | None: + def _getStringValueByNamespaceName(self, namespaceName: str) -> str|None: ''' Gets a single str value (a summary if necessary) for a supported 'namespace:name'. @@ -1882,7 +1882,7 @@ def _getPluralAttribute(self, attributeName: str) -> tuple[str, ...]: raise AttributeError(f'invalid attributeName: {attributeName}') - def _getSingularAttribute(self, attributeName: str) -> str | None: + def _getSingularAttribute(self, attributeName: str) -> str|None: ''' This returns a single string (perhaps a summary) for supported uniqueNames, grandfathered workIds, and grandfathered workId abbrevations. @@ -2005,7 +2005,7 @@ def _isStandardNamespaceName(namespaceName: str) -> bool: >>> metadata.Metadata._isStandardNamespaceName('average duration') False ''' - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.NAMESPACE_NAME_TO_PROPERTY_DESCRIPTION.get(namespaceName, None) ) if prop is None: @@ -2044,7 +2044,7 @@ def _isContributorUniqueName(uniqueName: str) -> bool: >>> metadata.Metadata._isContributorUniqueName('average duration') False ''' - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.UNIQUE_NAME_TO_PROPERTY_DESCRIPTION.get(uniqueName, None) ) if prop is None: @@ -2094,7 +2094,7 @@ def _isContributorNamespaceName(namespaceName: str) -> bool: >>> metadata.Metadata._isContributorNamespaceName('average duration') False ''' - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.NAMESPACE_NAME_TO_PROPERTY_DESCRIPTION.get(namespaceName, None) ) if prop is None: @@ -2132,7 +2132,7 @@ def _namespaceNameNeedsArticleNormalization(namespaceName: str) -> bool: >>> metadata.Metadata._namespaceNameNeedsArticleNormalization('average duration') False ''' - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.NAMESPACE_NAME_TO_PROPERTY_DESCRIPTION.get(namespaceName, None) ) if prop is None: @@ -2141,7 +2141,7 @@ def _namespaceNameNeedsArticleNormalization(namespaceName: str) -> bool: return prop.needsArticleNormalization @staticmethod - def _contributorRoleToUniqueName(role: str | None) -> str: + def _contributorRoleToUniqueName(role: str|None) -> str: ''' Translates a contributor role to a standard uniqueName that should be used to store that contributor. For standard contributor @@ -2172,7 +2172,7 @@ def _contributorRoleToUniqueName(role: str | None) -> str: if role is None: return 'otherContributor' - prop: PropertyDescription | None = ( + prop: PropertyDescription|None = ( properties.UNIQUE_NAME_TO_PROPERTY_DESCRIPTION.get(role, None) ) @@ -2207,7 +2207,7 @@ def _get(self, name: str, isCustom: bool) -> tuple[ValueType, ...]: ' Call addCustom/setCustom/getCustom for custom names.') name = uniqueName - valueList: list[ValueType] | None = self._contents.get(name, None) + valueList: list[ValueType]|None = self._contents.get(name, None) if not valueList: # return empty tuple @@ -2216,7 +2216,7 @@ def _get(self, name: str, isCustom: bool) -> tuple[ValueType, ...]: # return a tuple containing contents of list return tuple(valueList) - def _add(self, name: str, value: t.Any | Iterable[t.Any], isCustom: bool): + def _add(self, name: str, value: t.Any|Iterable[t.Any], isCustom: bool): ''' Adds a single item or multiple items with this name, leaving any existing items with this name in place. @@ -2247,7 +2247,7 @@ def _add(self, name: str, value: t.Any | Iterable[t.Any], isCustom: bool): for v in value: convertedValues.append(self._convertValue(name, v)) - prevValues: list[ValueType] | None = self._contents.get(name, None) + prevValues: list[ValueType]|None = self._contents.get(name, None) if not prevValues: # None or [] # set the convertedValues list in there # it's always a list, even if there's only one value @@ -2257,7 +2257,7 @@ def _add(self, name: str, value: t.Any | Iterable[t.Any], isCustom: bool): self._contents[name] = prevValues + convertedValues # noinspection GrazieInspection - def _set(self, name: str, value: t.Any | Iterable[t.Any], isCustom: bool): + def _set(self, name: str, value: t.Any|Iterable[t.Any], isCustom: bool): ''' Sets a single item or multiple items with this name, replacing any existing items with this name. If isCustom is False, the name must @@ -2350,7 +2350,7 @@ def _convertValue(uniqueName: str, value: t.Any) -> ValueType: ... metadata.DateBetween(['1938', '1939'])) ''' - valueType: type[ValueType] | None = properties.UNIQUE_NAME_TO_VALUE_TYPE.get( + valueType: type[ValueType]|None = properties.UNIQUE_NAME_TO_VALUE_TYPE.get( uniqueName, None ) originalValue: t.Any = value diff --git a/music21/metadata/bundles.py b/music21/metadata/bundles.py index 1f5ad2a6a9..5763e3fec2 100644 --- a/music21/metadata/bundles.py +++ b/music21/metadata/bundles.py @@ -274,15 +274,15 @@ class MetadataBundle(prebase.ProtoM21Object): # INITIALIZER # - def __init__(self, expr: 'music21.corpus.corpora.Corpus' | str | None = None): + def __init__(self, expr: 'music21.corpus.corpora.Corpus'|str|None = None): from music21 import corpus self._metadataEntries: OrderedDict[str, MetadataEntry] = OrderedDict() if not isinstance(expr, (str, corpus.corpora.Corpus, type(None))): raise MetadataBundleException('Need to take a string, corpus, or None as expression') - self._corpus: corpus.corpora.Corpus | None = None - self._name: str | None + self._corpus: corpus.corpora.Corpus|None = None + self._name: str|None if isinstance(expr, corpus.corpora.Corpus): self._name = expr.name @@ -1113,7 +1113,7 @@ def read(self, filePath=None): def search( self, - query: str | None = None, + query: str|None = None, field=None, *, fileExtensions: Iterable[str] = (), diff --git a/music21/metadata/primitives.py b/music21/metadata/primitives.py index 3e20dde4a3..ea7208bc46 100644 --- a/music21/metadata/primitives.py +++ b/music21/metadata/primitives.py @@ -88,18 +88,18 @@ class Date(prebase.ProtoM21Object): def __init__(self, *, - year: int | str | None = None, - month: int | str | None = None, - day: int | str | None = None, - hour: int | str | None = None, - minute: int | str | None = None, - second: int | float | str | None = None, - yearError: str | None = None, - monthError: str | None = None, - dayError: str | None = None, - hourError: str | None = None, - minuteError: str | None = None, - secondError: str | None = None): + year: int|str|None = None, + month: int|str|None = None, + day: int|str|None = None, + hour: int|str|None = None, + minute: int|str|None = None, + second: int|float|str|None = None, + yearError: str|None = None, + monthError: str|None = None, + dayError: str|None = None, + hourError: str|None = None, + minuteError: str|None = None, + secondError: str|None = None): if year is not None and yearError is None: year, yearError = self._stripError(year) if month is not None and monthError is None: @@ -115,21 +115,21 @@ def __init__(self, self._sanityCheck(year=year, month=month, day=day, hour=hour, minute=minute, second=second) - self.year = t.cast(int | None, year) - self.month = t.cast(int | None, month) - self.day = t.cast(int | None, day) - self.hour = t.cast(int | None, hour) - self.minute = t.cast(int | None, minute) - self.second = t.cast(int | None, second) + self.year = t.cast(int|None, year) + self.month = t.cast(int|None, month) + self.day = t.cast(int|None, day) + self.hour = t.cast(int|None, hour) + self.minute = t.cast(int|None, minute) + self.second = t.cast(int|None, second) # error: can be 'approximate', 'uncertain' or None. # None is assumed to be certain - self.yearError: str | None = yearError - self.monthError: str | None = monthError - self.dayError: str | None = dayError - self.hourError: str | None = hourError - self.minuteError: str | None = minuteError - self.secondError: str | None = secondError + self.yearError: str|None = yearError + self.monthError: str|None = monthError + self.dayError: str|None = dayError + self.hourError: str|None = hourError + self.minuteError: str|None = minuteError + self.secondError: str|None = secondError self.attrNames = ('year', 'month', 'day', 'hour', 'minute', 'second') # SPECIAL METHODS # @@ -177,8 +177,8 @@ def __str__(self): # PRIVATE METHODS # def _stripError(self, - value: int | float | str, - ) -> tuple[int, str | None]: + value: int|float|str, + ) -> tuple[int, str|None]: r''' Strip error symbols from a numerical value. Return cleaned source and sym. Only one error symbol is expected per string. @@ -195,7 +195,7 @@ def _stripError(self, >>> d._stripError('4.43') (4, None) ''' - uncertainty: str | None = None + uncertainty: str|None = None if isinstance(value, str): # if a number, let pass sym = self.approximateSymbols + self.uncertainSymbols + self.priorTimeSymbols found = None @@ -357,8 +357,8 @@ def loadStr(self, dateStr: str) -> None: >>> d.minute, d.second (50, 32) ''' - post: list[int | None] = [] - postError: list[str | None] = [] + post: list[int|None] = [] + postError: list[str|None] = [] dateStr = dateStr.replace(':', '/') dateStr = dateStr.replace(' ', '') for chunk in dateStr.split('/'): @@ -479,7 +479,7 @@ def __init__(self, relevance: str = 'certain'): # store an array of values marking if date data itself # is certain, approximate, or uncertain # here, dataError is relevance - self._dataUncertainty: list[str | None] = [] + self._dataUncertainty: list[str|None] = [] self.relevance = relevance # will use property # SPECIAL METHODS # @@ -841,16 +841,16 @@ class Text(prebase.ProtoM21Object): # INITIALIZER # def __init__(self, - data: str | Text = '', - language: str | None = None, - isTranslated: bool | None = None, # True, False, or None (unknown) - encodingScheme: str | None = None): + data: str|Text = '', + language: str|None = None, + isTranslated: bool|None = None, # True, False, or None (unknown) + encodingScheme: str|None = None): if isinstance(data, Text): # accessing private attributes here; not desirable - self._data: str | Text = data._data - self._language: str | None = data._language - self.isTranslated: bool | None = data.isTranslated - self.encodingScheme: str | None = data.encodingScheme + self._data: str|Text = data._data + self._language: str|None = data._language + self.isTranslated: bool|None = data.isTranslated + self.encodingScheme: str|None = data.encodingScheme else: self._data = data self._language = language @@ -1000,9 +1000,9 @@ class Copyright(Text): ''' def __init__(self, - data: str | Text = '', - language: str | None = None, - isTranslated: bool | None = None, # True, False, or None (unknown) + data: str|Text = '', + language: str|None = None, + isTranslated: bool|None = None, # True, False, or None (unknown) *, role=None): super().__init__(data, language, isTranslated) self.role = role @@ -1081,11 +1081,11 @@ class Contributor(prebase.ProtoM21Object): def __init__(self, *, - name: str | Text | None = None, - names: Iterable[str | Text] = (), - role: str | Text | None = None, - birth: None | DateSingle | str = None, - death: None | DateSingle | str = None, + name: str|Text|None = None, + names: Iterable[str|Text] = (), + role: str|Text|None = None, + birth: None|DateSingle|str = None, + death: None|DateSingle|str = None, **keywords): self._role = None if role: @@ -1110,8 +1110,8 @@ def __init__(self, # store the nationality, if known (not currently used) self._nationality: list[Text] = [] - self.birth: DateSingle | None = None - self.death: DateSingle | None = None + self.birth: DateSingle|None = None + self.death: DateSingle|None = None if birth is not None: if not isinstance(birth, DateSingle): @@ -1211,7 +1211,7 @@ def __eq__(self, other) -> bool: # PUBLIC METHODS # - def age(self) -> datetime.timedelta | None: + def age(self) -> datetime.timedelta|None: r''' Calculate the age at death of the Contributor, returning a datetime.timedelta object. @@ -1606,8 +1606,8 @@ def testDateSelection(self): Copyright, ) -DateParseType = Date | datetime.datetime | str -ValueType = DatePrimitive | Text | Contributor | Copyright | int +DateParseType = Date|datetime.datetime|str +ValueType = DatePrimitive|Text|Contributor|Copyright|int if __name__ == '__main__': diff --git a/music21/metadata/properties.py b/music21/metadata/properties.py index 389f1e32b8..87f1195ee0 100644 --- a/music21/metadata/properties.py +++ b/music21/metadata/properties.py @@ -47,11 +47,11 @@ class PropertyDescription: metadata, and is the tuple element type clients will always receive from md['uniqueName'] or md['namespace:name']. ''' - uniqueName: str | None = None + uniqueName: str|None = None name: str = '' namespace: str = '' - oldMusic21Abbrev: str | None = None - oldMusic21WorkId: str | None = None + oldMusic21Abbrev: str|None = None + oldMusic21WorkId: str|None = None valueType: type[ValueType] = Text needsArticleNormalization: bool = False isContributor: bool = False diff --git a/music21/meter/base.py b/music21/meter/base.py index 1c8614bc6d..34322e4362 100644 --- a/music21/meter/base.py +++ b/music21/meter/base.py @@ -533,7 +533,7 @@ def __init__(self, value: str = '4/4', divisions=None, **keywords): if value is None: value = f'{defaults.meterNumerator}/{defaults.meterDenominatorBeatType}' - self._overriddenBarDuration: duration.Duration | None = None + self._overriddenBarDuration: duration.Duration|None = None self.symbol: str = '' self.displaySequence: MeterSequence = _SENTINEL_METER_SEQUENCE self.beatSequence: MeterSequence = _SENTINEL_METER_SEQUENCE @@ -1246,7 +1246,7 @@ def _setDefaultAccentWeights(self, depth: int = 3) -> None: ''' # NOTE: this is a performance critical method - firstPartitionForm: MeterSequence | int | None + firstPartitionForm: MeterSequence|int|None # create a scratch MeterSequence for structure tsStr = f'{self.numerator}/{self.denominator}' @@ -1305,7 +1305,7 @@ def _setDefaultAccentWeights(self, depth: int = 3) -> None: # -------------------------------------------------------------------------- # access data for other processing - def getBeams(self, srcList, measureStartOffset=0.0) -> list[beam.Beams | None]: + def getBeams(self, srcList, measureStartOffset=0.0) -> list[beam.Beams|None]: ''' Given a qLen position and an iterable of Music21Objects, return a list of Beams objects. @@ -1621,7 +1621,7 @@ def getAccent(self, qLenPos: OffsetQL) -> bool: return False def setAccentWeight(self, - weights: Sequence[float] | float, + weights: Sequence[float]|float, level: int = 0) -> None: ''' Set accent weight, or floating point scalars, for the accent MeterSequence. diff --git a/music21/meter/core.py b/music21/meter/core.py index ba06fb2cb2..1b665dd580 100644 --- a/music21/meter/core.py +++ b/music21/meter/core.py @@ -56,7 +56,7 @@ class MeterTerminal(prebase.ProtoM21Object, SlottedObjectMixin): ) # INITIALIZER # - def __init__(self, slashNotation: str | None = None, weight=1): + def __init__(self, slashNotation: str|None = None, weight=1): # because of how they are copied, MeterTerminals must not have any # initialization parameters without defaults self._duration = None @@ -1780,7 +1780,7 @@ def offsetToWeight(self, qLenPos): iMatch = self.offsetToIndex(qLenPos) return opFrac(self[iMatch].weight) - def offsetToDepth(self, qLenPos, align='quantize', index: int | None = None): + def offsetToDepth(self, qLenPos, align='quantize', index: int|None = None): ''' Given a qLenPos, return the maximum available depth at this position. diff --git a/music21/meter/tools.py b/music21/meter/tools.py index 5c9b1f0933..924674a25f 100644 --- a/music21/meter/tools.py +++ b/music21/meter/tools.py @@ -132,7 +132,7 @@ def slashMixedToFraction(valueSrc: str) -> tuple[NumDenomTuple, bool]: * Changed in v7: new location and returns a tuple as first value. ''' - pre: list[NumDenom | tuple[int, None]] = [] + pre: list[NumDenom|tuple[int, None]] = [] summedNumerator = False value = valueSrc.strip() # rem whitespace value = value.split('+') diff --git a/music21/midi/__init__.py b/music21/midi/__init__.py index b8be2983ba..78adb03f80 100644 --- a/music21/midi/__init__.py +++ b/music21/midi/__init__.py @@ -467,31 +467,31 @@ class MidiEvent(prebase.ProtoM21Object): ''' # pylint: disable=redefined-builtin def __init__(self, - track: MidiTrack | None = None, + track: MidiTrack|None = None, type=None, time: int = 0, - channel: int | None = None): - self.track: MidiTrack | None = track # a MidiTrack object + channel: int|None = None): + self.track: MidiTrack|None = track # a MidiTrack object self.type = type self.time: int = time - self.channel: int | None = channel + self.channel: int|None = channel - self.parameter1: int | bytes | None = None # pitch or first data value - self.parameter2: int | bytes | None = None # velocity or second data value + self.parameter1: int|bytes|None = None # pitch or first data value + self.parameter2: int|bytes|None = None # velocity or second data value # data is a property... # if this is a Note on/off, need to store original # pitch space value in order to determine if this has a microtone - self.centShift: int | None = None + self.centShift: int|None = None # store a reference to a corresponding event # if a noteOn, store the note off, and vice versa # circular ref -- but modern Python will garbage collect it. - self.correspondingEvent: MidiEvent | None = None + self.correspondingEvent: MidiEvent|None = None # store and pass on a running status if found - self.lastStatusByte: int | None = None + self.lastStatusByte: int|None = None @property def sortOrder(self) -> int: diff --git a/music21/midi/translate.py b/music21/midi/translate.py index 65f559d343..d37dd6590d 100644 --- a/music21/midi/translate.py +++ b/music21/midi/translate.py @@ -321,7 +321,7 @@ def midiEventsToNote( eventTuple: tuple[tuple[int, midi.MidiEvent], tuple[int, midi.MidiEvent]], ticksPerQuarter: int = defaults.ticksPerQuarter, -) -> note.Note | note.Unpitched: +) -> note.Note|note.Unpitched: # noinspection PyShadowingNames ''' Convert from a tuple of two tuples of an int and a midi.MidiEvent objects @@ -392,7 +392,7 @@ def midiEventsToNote( tOn, eOn = eventTuple[0] tOff, unused_eOff = eventTuple[1] - returnClass: type[note.Unpitched] | type[note.Note] + returnClass: type[note.Unpitched]|type[note.Note] if eOn.channel == 10: returnClass = note.Unpitched else: @@ -425,12 +425,12 @@ def midiEventsToNote( nr.volume.velocityIsRelative = False # not relative coming from MIDI # n._midiVelocity = eOn.velocity - return t.cast(note.Note | note.Unpitched, nr) + return t.cast(note.Note|note.Unpitched, nr) def noteToMidiEvents( - inputM21: note.Note | note.Unpitched, *, includeDeltaTime=True, channel=1 -) -> list[midi.DeltaTime | midi.MidiEvent]: + inputM21: note.Note|note.Unpitched, *, includeDeltaTime=True, channel=1 +) -> list[midi.DeltaTime|midi.MidiEvent]: # noinspection PyShadowingNames ''' Translate a music21 Note to a list of four MIDI events -- @@ -476,7 +476,7 @@ def noteToMidiEvents( n = inputM21 mt = None # use a midi track set to None - eventList: list[midi.DeltaTime | midi.MidiEvent] = [] + eventList: list[midi.DeltaTime|midi.MidiEvent] = [] if includeDeltaTime: dt = midiModule.DeltaTime(mt, channel=channel) @@ -630,7 +630,7 @@ def midiEventsToChord( v.velocityIsRelative = False # velocity is absolute coming from volumes.append(v) - returnClass: type[percussion.PercussionChord] | type[chord.Chord] + returnClass: type[percussion.PercussionChord]|type[chord.Chord] if any_channel_10: returnClass = percussion.PercussionChord else: @@ -663,7 +663,7 @@ def midiEventsToChord( def chordToMidiEvents( inputM21: chord.ChordBase, *, includeDeltaTime=True, channel=1 -) -> list[midi.DeltaTime | midi.MidiEvent]: +) -> list[midi.DeltaTime|midi.MidiEvent]: # noinspection PyShadowingNames ''' Translates a :class:`~music21.chord.Chord` object to a @@ -696,7 +696,7 @@ def chordToMidiEvents( ''' from music21 import midi as midiModule mt = None # midi track - eventList: list[midi.DeltaTime | midi.MidiEvent] = [] + eventList: list[midi.DeltaTime|midi.MidiEvent] = [] c = inputM21 # temporary storage for setting correspondence @@ -825,7 +825,7 @@ def instrumentToMidiEvents(inputM21, # Meta events def midiEventsToInstrument( - eventList: midi.MidiEvent | tuple[int, midi.MidiEvent] + eventList: midi.MidiEvent|tuple[int, midi.MidiEvent] ) -> instrument.Instrument: ''' Convert a single MIDI event into a music21 Instrument object. @@ -1061,7 +1061,7 @@ def midiEventsToKey(eventList) -> key.Key: def keySignatureToMidiEvents( ks: key.KeySignature, includeDeltaTime=True -) -> list[midi.DeltaTime | midi.MidiEvent]: +) -> list[midi.DeltaTime|midi.MidiEvent]: # noinspection PyShadowingNames r''' Convert a single :class:`~music21.key.Key` or @@ -1087,7 +1087,7 @@ def keySignatureToMidiEvents( ''' from music21 import midi as midiModule mt = None # use a midi track set to None - eventList: list[midi.DeltaTime | midi.MidiEvent] = [] + eventList: list[midi.DeltaTime|midi.MidiEvent] = [] if includeDeltaTime: dt = midiModule.DeltaTime(track=mt) # leave dt.time set to zero; will be shifted later as necessary @@ -1130,7 +1130,7 @@ def midiEventsToTempo(eventList): def tempoToMidiEvents( tempoIndication: tempo.MetronomeMark, includeDeltaTime=True, -) -> list[midi.DeltaTime | midi.MidiEvent] | None: +) -> list[midi.DeltaTime|midi.MidiEvent]|None: # noinspection PyShadowingNames r''' Given any TempoIndication, convert it to list of :class:`~music21.midi.MidiEvent` @@ -1186,7 +1186,7 @@ def tempoToMidiEvents( if tempoIndication.number is None and tempoIndication.numberSounding is None: return None mt = None # use a midi track set to None - eventList: list[midi.DeltaTime | midi.MidiEvent] = [] + eventList: list[midi.DeltaTime|midi.MidiEvent] = [] if includeDeltaTime: dt = midiModule.DeltaTime(track=mt) eventList.append(dt) @@ -1213,8 +1213,8 @@ def getPacketFromMidiEvent( trackId: int, offset: int, midiEvent: midi.MidiEvent, - obj: base.Music21Object | None = None, - lastInstrument: instrument.Instrument | None = None + obj: base.Music21Object|None = None, + lastInstrument: instrument.Instrument|None = None ) -> dict[str, t.Any]: ''' Pack a dictionary of parameters for each event. @@ -1271,7 +1271,7 @@ def getPacketFromMidiEvent( # noinspection PyTypeChecker def elementToMidiEventList( el: base.Music21Object -) -> list[midi.MidiEvent | midi.MidiEvent] | None: +) -> list[midi.MidiEvent|midi.MidiEvent]|None: ''' Return a list of MidiEvents (or None) from a Music21Object, assuming that dynamics have already been applied, etc. @@ -1634,7 +1634,7 @@ def assignPacketsToChannels( def filterPacketsByTrackId( packetsSrc: list[dict[str, t.Any]], - trackIdFilter: int | None = None, + trackIdFilter: int|None = None, ) -> list[dict[str, t.Any]]: ''' Given a list of Packet dictionaries, return a list of @@ -1669,7 +1669,7 @@ def filterPacketsByTrackId( def packetsToDeltaSeparatedEvents( packets: list[dict[str, t.Any]], midiTrack: midi.MidiTrack, -) -> list[midi.MidiEvent | midi.DeltaTime]: +) -> list[midi.MidiEvent|midi.DeltaTime]: ''' Given a list of packets (which already contain MidiEvent objects) return a list of those Events with proper delta times between them. @@ -1682,7 +1682,7 @@ def packetsToDeltaSeparatedEvents( ''' from music21.midi import DeltaTime - events: list[midi.MidiEvent | DeltaTime] = [] + events: list[midi.MidiEvent|DeltaTime] = [] lastOffset = 0 for packet in packets: midiEvent = packet['midiEvent'] @@ -1888,7 +1888,7 @@ def midiTrackToStream( ticksPerQuarter: int = defaults.ticksPerQuarter, quantizePost=True, inputM21=None, - conductorPart: stream.Part | None = None, + conductorPart: stream.Part|None = None, isFirst: bool = False, quarterLengthDivisors: Sequence[int] = (), **keywords @@ -2088,7 +2088,7 @@ def midiTrackToStream( if conductorPart is not None: insertConductorEvents(conductorPart, s, isFirst=isFirst) - meterStream: stream.Stream | None = None + meterStream: stream.Stream|None = None if conductorPart is not None: ts_iter = conductorPart['TimeSignature'] if ts_iter: @@ -2244,8 +2244,8 @@ def conductorStream(s: stream.Stream) -> stream.Part: def channelInstrumentData( s: stream.Stream, - acceptableChannelList: list[int] | None = None, -) -> tuple[dict[int | None, int], list[int]]: + acceptableChannelList: list[int]|None = None, +) -> tuple[dict[int|None, int], list[int]]: ''' Read through Stream `s` and finding instruments in it, return a 2-tuple, the first a dictionary mapping MIDI program numbers to channel numbers, @@ -2474,7 +2474,7 @@ def packetStorageFromSubstreamList( def updatePacketStorageWithChannelInfo( packetStorage: dict[int, dict[str, t.Any]], - channelByInstrument: dict[int | None, int | None], + channelByInstrument: dict[int|None, int|None], ) -> None: ''' Take the packetStorage dictionary and using information @@ -2596,7 +2596,7 @@ def midiTracksToStreams( midiTracks: list[midi.MidiTrack], ticksPerQuarter: int = defaults.ticksPerQuarter, quantizePost=True, - inputM21: stream.Score | None = None, + inputM21: stream.Score|None = None, **keywords ) -> stream.Score: ''' @@ -2641,7 +2641,7 @@ def streamToMidiFile( inputM21: stream.Stream, *, addStartDelay: bool = False, - acceptableChannelList: list[int] | None = None, + acceptableChannelList: list[int]|None = None, ) -> midi.MidiFile: # noinspection PyShadowingNames ''' @@ -3790,7 +3790,7 @@ def testMidiExportVelocityB(self) -> None: qlList = [1.5] * 6 + [1] * 8 + [2] * 6 + [1.5] * 8 + [1] * 4 - c: note.Rest | chord.Chord + c: note.Rest|chord.Chord for j, ql in enumerate(qlList): if random.random() > 0.6: c = note.Rest() diff --git a/music21/musicxml/archiveTools.py b/music21/musicxml/archiveTools.py index f79c85507f..fe4617bca6 100644 --- a/music21/musicxml/archiveTools.py +++ b/music21/musicxml/archiveTools.py @@ -47,7 +47,7 @@ def compressAllXMLFiles(*, deleteOriginal=False): ) -def compressXML(filename: str | pathlib.Path, +def compressXML(filename: str|pathlib.Path, *, deleteOriginal=False, silent=False, @@ -99,7 +99,7 @@ def compressXML(filename: str | pathlib.Path, return True -def uncompressMXL(filename: str | pathlib.Path, +def uncompressMXL(filename: str|pathlib.Path, *, deleteOriginal=False, strictMxlCheck=True) -> bool: diff --git a/music21/musicxml/helpers.py b/music21/musicxml/helpers.py index f103d89f3a..5d8a6ef496 100644 --- a/music21/musicxml/helpers.py +++ b/music21/musicxml/helpers.py @@ -238,7 +238,7 @@ def synchronizeIdsToM21(element: ET.Element, m21Object: Music21Object): def synchronizeIdsToXML( element: ET.Element, - m21Object: prebase.ProtoM21Object | None + m21Object: prebase.ProtoM21Object|None ) -> None: # noinspection PyTypeChecker ''' @@ -295,8 +295,8 @@ def setM21AttributeFromAttribute( m21El: t.Any, xmlEl: ET.Element, xmlAttributeName: str, - attributeName: str | None = None, - transform: Callable[[str], t.Any] | None = None, + attributeName: str|None = None, + transform: Callable[[str], t.Any]|None = None, ) -> None: ''' If xmlEl has at least one element of tag==tag with some text. If @@ -348,8 +348,8 @@ def setXMLAttributeFromAttribute( m21El: t.Any, xmlEl: ET.Element, xmlAttributeName: str, - attributeName: str | None = None, - transform: Callable[[t.Any], t.Any] | None = None + attributeName: str|None = None, + transform: Callable[[t.Any], t.Any]|None = None ): ''' If m21El has at least one element of tag==tag with some text. If diff --git a/music21/musicxml/m21ToXml.py b/music21/musicxml/m21ToXml.py index 6c0dfffcc9..bcc3848b8b 100644 --- a/music21/musicxml/m21ToXml.py +++ b/music21/musicxml/m21ToXml.py @@ -141,7 +141,7 @@ def normalizeColor(color: str) -> str: return color.upper() -def getMetadataFromContext(s: stream.Stream) -> metadata.Metadata | None: +def getMetadataFromContext(s: stream.Stream) -> metadata.Metadata|None: # noinspection PyShadowingNames ''' Get metadata from site or context, so that a Part @@ -178,11 +178,11 @@ def _setTagTextFromAttribute( m21El: t.Any, xmlEl: Element, tag: str, - attributeName: str | None = None, + attributeName: str|None = None, *, - transform: t.Callable[[t.Any], t.Any] | None = None, + transform: t.Callable[[t.Any], t.Any]|None = None, forceEmpty: bool = False -) -> Element | None: +) -> Element|None: ''' If m21El has an attribute called attributeName, create a new SubElement for xmlEl and set its text to the value of the m21El attribute. @@ -263,11 +263,11 @@ class GeneralObjectExporter: ('Music21Object', 'fromMusic21Object'), ]) - def __init__(self, obj: prebase.ProtoM21Object | None = None): + def __init__(self, obj: prebase.ProtoM21Object|None = None): self.generalObj = obj self.makeNotation: bool = True - def parse(self, obj: prebase.ProtoM21Object | None = None) -> bytes: + def parse(self, obj: prebase.ProtoM21Object|None = None) -> bytes: r''' Return a bytes object representation of anything from a Score to a single pitch. @@ -1368,7 +1368,7 @@ class ScoreExporter(XMLExporterBase, PartStaffExporterMixin): a musicxml Element. ''' - def __init__(self, score: stream.Score | None = None, makeNotation: bool = True): + def __init__(self, score: stream.Score|None = None, makeNotation: bool = True): super().__init__() if score is None: # should not be done this way. @@ -1377,14 +1377,14 @@ def __init__(self, score: stream.Score | None = None, makeNotation: bool = True) self.stream = score self.xmlRoot = Element('score-partwise', version=defaults.musicxmlVersion) - self.mxIdentification: Element | None = None + self.mxIdentification: Element|None = None - self.scoreMetadata: metadata.Metadata | None = None + self.scoreMetadata: metadata.Metadata|None = None - self.spannerBundle: spanner.SpannerBundle | None = None - self.meterStream: stream.Stream[meter.TimeSignatureBase] | None = None + self.spannerBundle: spanner.SpannerBundle|None = None + self.meterStream: stream.Stream[meter.TimeSignatureBase]|None = None self.scoreLayouts: list[layout.ScoreLayout] = [] - self.firstScoreLayout: layout.ScoreLayout | None = None + self.firstScoreLayout: layout.ScoreLayout|None = None self.textBoxes: list[text.TextBox] = [] self.highestTime = 0.0 @@ -1397,8 +1397,8 @@ def __init__(self, score: stream.Score | None = None, makeNotation: bool = True) self.instrumentsByStream: dict[int, stream.Stream] = {} self.instrumentList: list[instrument.Instrument] = [] - self.instrumentIdList: list[str | None] = [] - self.midiChannelList: list[int | None] = [] + self.instrumentIdList: list[str|None] = [] + self.midiChannelList: list[int|None] = [] self.parts: list[stream.Part] = [] @@ -2301,8 +2301,8 @@ def setIdentification(self) -> Element: def metadataToMiscellaneous( self, - md: metadata.Metadata | None = None - ) -> Element | None: + md: metadata.Metadata|None = None + ) -> Element|None: # noinspection PyShadowingNames ''' Returns an mxMiscellaneous of information from metadata object md or @@ -2373,7 +2373,7 @@ def metadataToMiscellaneous( # We have already emitted all the copyrights. continue - namespaceName: str | None = md.uniqueNameToNamespaceName(uniqueName) + namespaceName: str|None = md.uniqueNameToNamespaceName(uniqueName) if namespaceName is None: namespaceName = uniqueName @@ -2498,7 +2498,7 @@ def setTitles(self) -> None: mxScoreHeader = self.xmlRoot mxWork = Element('work') # TODO: work-number - firstTitleFound: metadata.Text | None = None + firstTitleFound: metadata.Text|None = None titles: tuple[metadata.Text, ...] = mdObj['title'] if titles: if firstTitleFound is None: @@ -2572,15 +2572,15 @@ class PartExporter(XMLExporterBase): } def __init__(self, - partObj: stream.Part | stream.Score | None = None, - parent: ScoreExporter | None = None): + partObj: stream.Part|stream.Score|None = None, + parent: ScoreExporter|None = None): super().__init__() # partObj can be a Score IF it has no parts within it. But better to # always have it be a Part if partObj is None: partObj = stream.Part() - self.stream: stream.Part | stream.Score = partObj + self.stream: stream.Part|stream.Score = partObj self.parent = parent # ScoreExporter self.xmlRoot = Element('part') @@ -2597,9 +2597,9 @@ def __init__(self, self.midiChannelList = parent.midiChannelList # shared list self.makeNotation = parent.makeNotation - self.previousPartStaffInGroup: stream.PartStaff | None = None + self.previousPartStaffInGroup: stream.PartStaff|None = None - self.instrumentStream: stream.Stream[instrument.Instrument] | None = None + self.instrumentStream: stream.Stream[instrument.Instrument]|None = None self.firstInstrumentObject = None # keep track of this so that we only put out new attributes when something @@ -2607,7 +2607,7 @@ def __init__(self, self.lastDivisions = None # The staffGroup to which this part belongs (if it belongs to one) - self.staffGroup: layout.StaffGroup | None = None + self.staffGroup: layout.StaffGroup|None = None self.spannerBundle = partObj.spannerBundle def parse(self): @@ -3064,8 +3064,8 @@ class MeasureExporter(XMLExporterBase): ignoreOnParseClasses = {'LayoutBase', 'Barline'} def __init__(self, - measureObj: stream.Measure | None = None, - parent: PartExporter | None = None): + measureObj: stream.Measure|None = None, + parent: PartExporter|None = None): super().__init__() if measureObj is None: # no point, but... self.stream = stream.Measure() @@ -3084,7 +3084,7 @@ def __init__(self, self.mxTranspose = None self.measureOffsetStart = 0.0 self.offsetInMeasure = 0.0 - self.currentVoiceId: int | str | None = None + self.currentVoiceId: int|str|None = None self.nextFreeVoiceNumber: int = 1 self.nextArpeggioNumber: int = 1 self.arpeggioNumbers: dict[expressions.ArpeggioMarkSpanner, int] = {} @@ -3198,7 +3198,7 @@ def moveBackward(self, byOffset: OffsetQL): def parseFlatElements( self, - m: stream.Measure | stream.Voice, + m: stream.Measure|stream.Voice, *, backupAfterwards: bool = False ) -> None: @@ -3214,7 +3214,7 @@ def parseFlatElements( voice number is used instead. ''' self.offsetInMeasure = 0.0 - voiceId: int | str | None + voiceId: int|str|None if isinstance(m, stream.Voice): if isinstance(m.id, int) and m.id < defaults.minIdNumberToConsiderMemoryLocation: voiceId = m.id @@ -3600,7 +3600,7 @@ def objectAttachedSpannersToNotations( self, obj: base.Music21Object, noteIndexInChord: int = 0, - objectSpannerBundle: spanner.SpannerBundle | None = None + objectSpannerBundle: spanner.SpannerBundle|None = None ) -> list[Element]: ''' return a list of from spanners related to the object that should appear @@ -3841,7 +3841,7 @@ def appendArpeggioMarkSpannersToNotations( if isinstance(obj, chord.Chord): sub_obj = obj[noteIndexInChord] - mxArpeggio: Element | None = None + mxArpeggio: Element|None = None if ams.type == 'non-arpeggio': min_note, max_note = ams.noteExtremes() # goes only on top and bottom note in chord @@ -4156,7 +4156,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): def setNoteInstrument(self, n: note.NotRest, mxNote: Element, - chordParent: chord.Chord | None): + chordParent: chord.Chord|None): ''' Insert tags if necessary, that is, when there is more than one instrument anywhere in the same musicxml . @@ -4170,7 +4170,7 @@ def setNoteInstrument(self, if n.isRest: return - searchingObject: note.NotRest | chord.Chord = chordParent if chordParent else n + searchingObject: note.NotRest|chord.Chord = chordParent if chordParent else n closest_inst = searchingObject.getInstrument(returnDefault=True) instance_to_use = None @@ -4298,7 +4298,7 @@ def restToXml(self, r: note.Rest): if r.stepShift != 0: mxDisplayStep = SubElement(mxRestTag, 'display-step') mxDisplayOctave = SubElement(mxRestTag, 'display-octave') - currentClef: clef.PitchClef | None = r.getContextByClass(clef.PitchClef) + currentClef: clef.PitchClef|None = r.getContextByClass(clef.PitchClef) if currentClef is None or not hasattr(currentClef, 'lowestLine'): currentClef = clef.TrebleClef() # this should not be common enough to @@ -4505,7 +4505,7 @@ def pitchToXml(self, p: pitch.Pitch): def unpitchedToXml(self, up: note.Unpitched, noteIndexInChord: int = 0, - chordParent: chord.ChordBase | None = None) -> Element: + chordParent: chord.ChordBase|None = None) -> Element: # noinspection PyShadowingNames ''' Convert an :class:`~music21.note.Unpitched` to a @@ -4584,7 +4584,7 @@ def fretNoteToXml(self, fretNote) -> Element: return mxFrameNote - def fretBoardToXml(self, fretBoard) -> Element | None: + def fretBoardToXml(self, fretBoard) -> Element|None: ''' The ChordWithFretBoard Object combines chord symbols with FretNote objects. @@ -4693,7 +4693,7 @@ def dealWithNotehead( self, mxNote: Element, n: note.GeneralNote, - chordParent: chord.Chord | None = None + chordParent: chord.Chord|None = None ) -> None: ''' Determine if an element needs to be added to this @@ -4824,7 +4824,7 @@ def noteToNotations( self, n: note.GeneralNote, noteIndexInChord: int = 0, - chordParent: chord.Chord | None = None + chordParent: chord.Chord|None = None ) -> list[Element]: ''' Take information from .expressions, @@ -5595,7 +5595,7 @@ def noChordToXml(self, cs: harmony.NoChord) -> Element: self.xmlRoot.append(mxHarmony) return mxHarmony - def romanNumeralToXml(self, rn: roman.RomanNumeral) -> Element | list[Element]: + def romanNumeralToXml(self, rn: roman.RomanNumeral) -> Element|list[Element]: ''' Convert a RomanNumeral object to either a chord (if .writeAsChord is True) or a Harmony XML Element. @@ -5752,7 +5752,7 @@ def romanNumeralToXml(self, rn: roman.RomanNumeral) -> Element | list[Element]: def chordSymbolToXml(self, cs: harmony.ChordSymbol, *, - append: bool = True) -> Element | list[Element]: + append: bool = True) -> Element|list[Element]: # noinspection PyShadowingNames ''' Convert a ChordSymbol object to either a chord (if .writeAsChord is True) @@ -5972,10 +5972,10 @@ def chordSymbolToXml(self, def setOffsetOptional(self, m21Obj: base.Music21Object, - mxObj: Element | None = None, + mxObj: Element|None = None, *, setSound: bool = True - ) -> Element | None: + ) -> Element|None: ''' If this object has an offset different from self.offsetInMeasure, then create and return an offset Element. @@ -5997,7 +5997,7 @@ def setOffsetOptional(self, def placeInDirection(self, mxObj: Element, - m21Obj: base.Music21Object | None = None, + m21Obj: base.Music21Object|None = None, *, setSound: bool = True ) -> Element: @@ -6387,7 +6387,7 @@ def rehearsalMarkToXml(self, rm: expressions.RehearsalMark) -> Element: def textExpressionToXml( self, - teOrRe: expressions.TextExpression | repeat.RepeatExpression + teOrRe: expressions.TextExpression|repeat.RepeatExpression ) -> Element: ''' Convert a TextExpression or RepeatExpression to a MusicXML mxDirection type. @@ -6416,7 +6416,7 @@ def wrapObjectInAttributes( self, objectToWrap: base.Music21Object, methodToMx: t.Callable[[t.Any], Element], - ) -> Element | None: + ) -> Element|None: # noinspection PyShadowingNames ''' given a Clef, KeySignature, or TimeSignature which is in .elements and not m.clef, @@ -6929,7 +6929,7 @@ def staffLayoutToXmlStaffDetails(self, staffLayout): # TODO: staff-size return mxStaffDetails - def timeSignatureToXml(self, ts: meter.TimeSignature | meter.SenzaMisuraTimeSignature): + def timeSignatureToXml(self, ts: meter.TimeSignature|meter.SenzaMisuraTimeSignature): ''' Returns a single ''' - initialPartStaffRoot: Element | None = None + initialPartStaffRoot: Element|None = None for i, ps in enumerate(group): staffNumber: int = i + 1 # 1-indexed thisPartStaffRoot: Element = self.getRootForPartStaff(ps) @@ -389,7 +389,7 @@ def processSubsequentPartStaff(self, DIVIDER_COMMENT = '========================= Measure [NNN] ==========================' PLACEHOLDER = '[NNN]' - def makeDivider(inner_sourceNumber: int | str) -> Element: + def makeDivider(inner_sourceNumber: int|str) -> Element: return Comment(DIVIDER_COMMENT.replace(PLACEHOLDER, str(inner_sourceNumber))) sourceMeasures = iter(source.findall('measure')) @@ -549,7 +549,7 @@ def isMultiAttribute(m21Class: type[M21ObjType], in this StaffGroup does not compare to the first instance of that class in the earliest staff where found (not necessarily the first) using `comparison`. ''' - initialM21Instance: M21ObjType | None = None + initialM21Instance: M21ObjType|None = None # noinspection PyShadowingNames for ps in group: # ps okay to reuse. if initialM21Instance is None: @@ -567,8 +567,8 @@ def isMultiAttribute(m21Class: type[M21ObjType], multiKey: bool = isMultiAttribute(KeySignature) multiMeter: bool = isMultiAttribute(TimeSignature, comparison='ratioEqual') - initialPartStaffRoot: Element | None = None - mxAttributes: Element | None = None + initialPartStaffRoot: Element|None = None + mxAttributes: Element|None = None for i, ps in enumerate(group): staffNumber: int = i + 1 # 1-indexed @@ -600,7 +600,7 @@ def isMultiAttribute(m21Class: type[M21ObjType], # Subsequent PartStaffs in group: set additional clefs on mxAttributes else: thisPartStaffRoot: Element = self.getRootForPartStaff(ps) - oldClef: Element | None = thisPartStaffRoot.find('measure/attributes/clef') + oldClef: Element|None = thisPartStaffRoot.find('measure/attributes/clef') if oldClef is not None and mxAttributes is not None: clefsInMxAttributesAlready = mxAttributes.findall('clef') if len(clefsInMxAttributesAlready) >= staffNumber: diff --git a/music21/musicxml/testPrimitive.py b/music21/musicxml/testPrimitive.py index 46d26d7907..7a110e4f18 100644 --- a/music21/musicxml/testPrimitive.py +++ b/music21/musicxml/testPrimitive.py @@ -2328,10 +2328,10 @@ + caesura|stress | unstress | other-articulation --> diff --git a/music21/musicxml/xmlSoundParser.py b/music21/musicxml/xmlSoundParser.py index c983c1b553..ff8c8aa62a 100644 --- a/music21/musicxml/xmlSoundParser.py +++ b/music21/musicxml/xmlSoundParser.py @@ -59,7 +59,7 @@ def xmlSound(self, mxSound: ET.Element) -> None: def setSound( self, mxSound: ET.Element, - mxDir: ET.Element | None, + mxDir: ET.Element|None, staffKey: int, totalOffset: float ) -> None: @@ -96,7 +96,7 @@ def setSound( def setSoundTempo( self, mxSound: ET.Element, - mxDir: ET.Element | None, + mxDir: ET.Element|None, staffKey: int, totalOffset: float ) -> None: diff --git a/music21/musicxml/xmlToM21.py b/music21/musicxml/xmlToM21.py index 9d11e33c7e..33ed8f1e7b 100644 --- a/music21/musicxml/xmlToM21.py +++ b/music21/musicxml/xmlToM21.py @@ -87,7 +87,7 @@ # ------------------------------------------------------------------------------ # Helpers... -def _clean(badStr: str | None) -> str | None: +def _clean(badStr: str|None) -> str|None: # need to remove badly-formed strings if badStr is None: return None @@ -96,7 +96,7 @@ def _clean(badStr: str | None) -> str | None: return goodStr -def strippedText(mxObj: ET.Element | None) -> str: +def strippedText(mxObj: ET.Element|None) -> str: ''' Returns the `mxObj.text.strip()` from an Element (or None) taking into account that `.text` might be None, or the @@ -1237,7 +1237,7 @@ def xmlMetadata(self, el=None, inputM21=None): def identificationToMetadata(self, identification: ET.Element, - inputM21: metadata.Metadata | None = None): + inputM21: metadata.Metadata|None = None): ''' Convert an tag, containing tags, tags, and tag. @@ -1351,7 +1351,7 @@ def processEncoding(self, encoding: ET.Element, md: metadata.Metadata) -> None: def creatorToContributor(self, creator: ET.Element, - inputM21: metadata.primitives.Contributor | None = None): + inputM21: metadata.primitives.Contributor|None = None): # noinspection PyShadowingNames ''' Given a tag, fill the necessary parameters of a Contributor. @@ -1434,9 +1434,9 @@ class PartParser(XMLParserBase): ''' def __init__(self, - mxPart: ET.Element | None = None, - mxScorePart: ET.Element | None = None, - parent: MusicXMLImporter | None = None): + mxPart: ET.Element|None = None, + mxScorePart: ET.Element|None = None, + parent: MusicXMLImporter|None = None): super().__init__() self.mxPart = mxPart self.mxScorePart = mxScorePart @@ -1462,29 +1462,29 @@ def __init__(self, self.staffReferenceList: list[StaffReferenceType] = [] - self.lastTimeSignature: meter.TimeSignature | None = None + self.lastTimeSignature: meter.TimeSignature|None = None self.lastMeasureWasShort = False self.lastMeasureOffset = 0.0 # a dict of clefs per staff number - self.lastClefs: dict[int, clef.Clef | None] = {NO_STAFF_ASSIGNED: clef.TrebleClef()} - self.activeTuplets: list[duration.Tuplet | None] = [None] * 7 + self.lastClefs: dict[int, clef.Clef|None] = {NO_STAFF_ASSIGNED: clef.TrebleClef()} + self.activeTuplets: list[duration.Tuplet|None] = [None] * 7 self.maxStaves = 1 # will be changed in measure parsing... self.lastMeasureNumber = 0 - self.lastNumberSuffix: str | None = None + self.lastNumberSuffix: str|None = None self.multiMeasureRestsToCapture = 0 - self.activeMultiMeasureRestSpanner: spanner.MultiMeasureRest | None = None + self.activeMultiMeasureRestSpanner: spanner.MultiMeasureRest|None = None - self.activeInstrument: instrument.Instrument | None = None + self.activeInstrument: instrument.Instrument|None = None self.firstMeasureParsed = False # has the first measure been parsed yet? self.activeAttributes = None # divisions, clef, etc. self.lastDivisions: int = defaults.divisionsPerQuarter # give a default value for testing self.appendToScoreAfterParse = True - self.lastMeasureParser: MeasureParser | None = None + self.lastMeasureParser: MeasureParser|None = None def parse(self) -> None: ''' @@ -1533,7 +1533,7 @@ def _fillAndInsertOttavasInPartStaff( for sp in spanners: if not isinstance(sp, spanner.Ottava): continue - spannerPart: stream.Part | None = None + spannerPart: stream.Part|None = None if partStaves: spannerPart = self._findFirstPartStaffContaining(sp.getFirst(), partStaves) else: @@ -1546,9 +1546,9 @@ def _fillAndInsertOttavasInPartStaff( def _findFirstPartStaffContaining( self, - obj: base.Music21Object | None, + obj: base.Music21Object|None, partStaves: list[stream.PartStaff] - ) -> stream.PartStaff | None: + ) -> stream.PartStaff|None: if obj is None: return None @@ -1609,7 +1609,7 @@ def parseXmlScorePart(self): # TODO: MusicXML 4.0: player tags - def getDefaultInstrument(self, mxScorePart: ET.Element | None = None) -> instrument.Instrument: + def getDefaultInstrument(self, mxScorePart: ET.Element|None = None) -> instrument.Instrument: # noinspection PyShadowingNames r''' Get a default instrument from the mxScorePart tag. @@ -1684,7 +1684,7 @@ def _adjustMidiData(mc): # TODO: elevation # TODO: store id attribute somewhere mxMIDIInstrument = mxScorePart.find('midi-instrument') - i: instrument.Instrument | None = None + i: instrument.Instrument|None = None if mxMIDIInstrument is not None: mxMidiProgram = mxMIDIInstrument.find('midi-program') mxMidiUnpitched = mxMIDIInstrument.find('midi-unpitched') @@ -2346,8 +2346,8 @@ class MeasureParser(SoundTagMixin, XMLParserBase): # and xmlSound are found in xmlSoundParser.py } def __init__(self, - mxMeasure: ET.Element | None = None, - parent: PartParser | None = None): + mxMeasure: ET.Element|None = None, + parent: PartParser|None = None): super().__init__() self.mxMeasure = mxMeasure @@ -2358,11 +2358,11 @@ def __init__(self, self.transposition = None self.spannerBundle = self.parent.spannerBundle self.staffReference: StaffReferenceType = {} - self.activeTuplets: list[duration.Tuplet | None] = self.parent.activeTuplets + self.activeTuplets: list[duration.Tuplet|None] = self.parent.activeTuplets self.useVoices = False - self.voicesById: dict[str | int, stream.Voice] = {} - self.voiceIndices: set[str | int] = set() + self.voicesById: dict[str|int, stream.Voice] = {} + self.voiceIndices: set[str|int] = set() self.staves = 1 self.activeAttributes = None @@ -2376,12 +2376,12 @@ def __init__(self, # key is a tuple of the # staff number (or None) and offsetMeasureNote, and the value is a # StaffLayout object. - self.staffLayoutObjects: dict[tuple[int | None, float], layout.StaffLayout] = {} + self.staffLayoutObjects: dict[tuple[int|None, float], layout.StaffLayout] = {} self.stream = stream.Measure() self.mxNoteList: list[ET.Element] = [] # for accumulating notes in chords self.mxLyricList: list[ET.Element] = [] # for accumulating lyrics assigned to chords - self.nLast: note.GeneralNote | None = None # for adding notes to spanners. + self.nLast: note.GeneralNote|None = None # for adding notes to spanners. # Sibelius 7.1 only puts a tag on the # first note of a chord, and MuseScore doesn't put one @@ -2389,7 +2389,7 @@ def __init__(self, # that we keep track of the last voice. # there is an effort to translate the voice text to an int, but if that fails (unlikely) # we store whatever we find - self.lastVoice: str | int | None = None + self.lastVoice: str|int|None = None # fullMeasureRest is unreliable because pickup measures # in Finale set but then define a type like "quarter", @@ -2399,7 +2399,7 @@ def __init__(self, # for keeping track of full-measureRests. self.restAndNoteCount = {'rest': 0, 'note': 0} - self.lastClefs: dict[int, clef.Clef | None] = self.parent.lastClefs + self.lastClefs: dict[int, clef.Clef|None] = self.parent.lastClefs self.parseIndex = 0 # what is the offset in the measure of the current note position? @@ -2410,7 +2410,7 @@ def __init__(self, # older versions of Finale put a forward tag at the end, but this # disguises the incomplete last measure. The PartParser will # pick this up from the last measure. - self.endedWithForwardTag: note.Rest | None = None + self.endedWithForwardTag: note.Rest|None = None @staticmethod def getStaffNumber(mxObjectOrNumber) -> int: @@ -2729,7 +2729,7 @@ def xmlToNote(self, mxNote: ET.Element) -> None: isRest = False # TODO: Unpitched - offsetIncrement: float | fractions.Fraction = 0.0 + offsetIncrement: float|fractions.Fraction = 0.0 if mxNote.find('rest') is not None: # it is a Rest isRest = True @@ -2742,7 +2742,7 @@ def xmlToNote(self, mxNote: ET.Element) -> None: isChord = True # first note of chord is not identified. voiceOfChord = mxNote.find('voice') if voiceOfChord is not None: - vIndex: str | int | None = voiceOfChord.text + vIndex: str|int|None = voiceOfChord.text if isinstance(vIndex, str): try: vIndex = int(vIndex) @@ -2887,7 +2887,7 @@ def xmlToChord(self, mxNoteList: list[ET.Element]) -> chord.ChordBase: self.spannerBundle.freePendingSpannedElementAssignment(c) return c - def xmlToSimpleNote(self, mxNote, freeSpanners=True) -> note.Note | note.Unpitched: + def xmlToSimpleNote(self, mxNote, freeSpanners=True) -> note.Note|note.Unpitched: # noinspection PyShadowingNames ''' Translate a MusicXML (without ) @@ -2935,7 +2935,7 @@ def xmlToSimpleNote(self, mxNote, freeSpanners=True) -> note.Note | note.Unpitch ''' d = self.xmlToDuration(mxNote) - n: note.Note | note.Unpitched + n: note.Note|note.Unpitched mxUnpitched = mxNote.find('unpitched') if mxUnpitched is None: @@ -3198,7 +3198,7 @@ def xmlToPitch(self, mxNote, inputM21=None): def xmlToUnpitched( self, mxUnpitched: ET.Element, - inputM21: note.Unpitched | None = None, + inputM21: note.Unpitched|None = None, ) -> note.Unpitched: ''' Set `displayStep` and `displayOctave` from `mxUnpitched`. @@ -3238,7 +3238,7 @@ def xmlToUnpitched( def xmlToAccidental( self, mxAccidental: ET.Element, - inputM21: pitch.Accidental | None = None, + inputM21: pitch.Accidental|None = None, ) -> pitch.Accidental: ''' >>> from xml.etree.ElementTree import fromstring as EL @@ -3751,7 +3751,7 @@ def flatten(mx, name): arpeggioType = 'non-arpeggio' else: arpeggioType = mxObj.get('direction') or 'normal' - idFound: str | None = mxObj.get('number') + idFound: str|None = mxObj.get('number') if idFound is None: arpeggio = expressions.ArpeggioMark(arpeggioType) n.expressions.append(arpeggio) @@ -3767,7 +3767,7 @@ def flatten(mx, name): self.spannerBundle.append(arpeggioSpanner) arpeggioSpanner.addSpannedElements(n) - mostRecentOrnament: expressions.Ornament | None = None + mostRecentOrnament: expressions.Ornament|None = None for mxObj in flatten(mxNotations, 'ornaments'): if mxObj.tag in xmlObjects.ORNAMENT_MARKS or mxObj.tag == 'accidental-mark': post = self.xmlOrnamentToExpression( @@ -3976,7 +3976,7 @@ def xmlOrnamentToExpression( self, mxObj, *, - mostRecentOrnament: expressions.Ornament | None = None + mostRecentOrnament: expressions.Ornament|None = None ): ''' Convert mxOrnament into a music21 ornament. @@ -4461,7 +4461,7 @@ def xmlToTuplets(self, mxNote: ET.Element) -> list[duration.Tuplet]: remainingTupletAmountToAccountFor = tup.tupletMultiplier() timeModTup = tup - returnTuplets: list[duration.Tuplet | None] = [None] * 8 + returnTuplets: list[duration.Tuplet|None] = [None] * 8 removeFromActiveTuplets = set() # a set of tuplets to set to stop... @@ -4514,7 +4514,7 @@ def xmlToTuplets(self, mxNote: ET.Element) -> list[duration.Tuplet]: tup.durationNormal = duration.durationTupleFromTypeDots(durType, dots) # TODO: combine start + stop into startStop. - tup.type = t.cast(t.Literal['start', 'stop', 'startStop', False] | None, + tup.type = t.cast(t.Literal['start', 'stop', 'startStop', False]|None, this_tuplet_type) bracketMaybe = mxTuplet.get('bracket') @@ -4605,7 +4605,7 @@ def updateLyricsFromList(self, n, lyricList): n.lyrics.append(lyricObj) currentLyricNumber += 1 - def xmlToLyric(self, mxLyric, inputM21=None) -> note.Lyric | None: + def xmlToLyric(self, mxLyric, inputM21=None) -> note.Lyric|None: # noinspection PyShadowingNames ''' Translate a MusicXML tag to a @@ -4766,13 +4766,13 @@ def insertInMeasureOrVoice(self, mxElement, el): def findM21VoiceFromXmlVoice( self, - mxVoice: ET.Element | None = None, - ) -> stream.Voice | None: + mxVoice: ET.Element|None = None, + ) -> stream.Voice|None: ''' Find the stream.Voice object from a tag or None. ''' m = self.stream - useVoice: str | int | None + useVoice: str|int|None if strippedText(mxVoice): useVoice = strippedText(mxVoice) try: @@ -4787,7 +4787,7 @@ def findM21VoiceFromXmlVoice( MusicXMLWarning) useVoice = 1 - thisVoice: stream.Voice | None = None + thisVoice: stream.Voice|None = None if useVoice in self.voicesById: thisVoice = self.voicesById[useVoice] elif int(useVoice) in self.voicesById: @@ -5008,7 +5008,7 @@ def xmlHarmony(self, mxHarmony): def xmlToChordSymbol( self, mxHarmony: ET.Element - ) -> harmony.ChordSymbol | harmony.NoChord | tablature.ChordWithFretBoard: + ) -> harmony.ChordSymbol|harmony.NoChord|tablature.ChordWithFretBoard: # noinspection PyShadowingNames ''' Convert a tag to a harmony.ChordSymbol object: @@ -5056,9 +5056,9 @@ def xmlToChordSymbol( # TODO: musicxml 4: attr: arrangement -- C/E or C over E etc. # TODO: offset # Element staff is covered by insertCoreAndReference in xmlHarmony() - b: pitch.Pitch | None = None - r: pitch.Pitch | None = None - inversion: int | None = None + b: pitch.Pitch|None = None + r: pitch.Pitch|None = None + inversion: int|None = None chordKind: str = '' chordKindStr: str = '' @@ -5122,7 +5122,7 @@ def xmlToChordSymbol( # TODO: musicxml 4: numeral -- pretty important. - cs_class: type[harmony.ChordSymbol | harmony.NoChord | tablature.ChordWithFretBoard] + cs_class: type[harmony.ChordSymbol|harmony.NoChord|tablature.ChordWithFretBoard] if mxFrame is not None: cs_class = tablature.ChordWithFretBoard elif chordKind == 'none': @@ -5260,7 +5260,7 @@ def setDirectionInDirectionType( self.setEditorial(mxDirection, sp) elif tag in ('coda', 'segno'): - rm: repeat.Segno | repeat.Coda + rm: repeat.Segno|repeat.Coda if tag == 'segno': rm = repeat.Segno() else: @@ -5637,7 +5637,7 @@ def handleTimeSignature(self, mxTime): def xmlToTimeSignature( self, mxTime: ET.Element - ) -> meter.TimeSignature | meter.SenzaMisuraTimeSignature: + ) -> meter.TimeSignature|meter.SenzaMisuraTimeSignature: # noinspection PyShadowingNames ''' Returns a TimeSignature or SenzaMisuraTimeSignature (for senza-misura) @@ -6030,8 +6030,8 @@ def handleStaffDetails(self, mxDetails): def xmlStaffLayoutFromStaffDetails( self, mxDetails, - m21staffLayout: layout.StaffLayout | None = None - ) -> layout.StaffLayout | None: + m21staffLayout: layout.StaffLayout|None = None + ) -> layout.StaffLayout|None: # noinspection PyShadowingNames ''' Returns a new StaffLayout object from staff-details or sets attributes on an existing one diff --git a/music21/note.py b/music21/note.py index 4b938cb81a..a1076b223e 100644 --- a/music21/note.py +++ b/music21/note.py @@ -226,14 +226,14 @@ def __init__(self, *, applyRaw: bool = False, syllabic: SyllabicChoices = None, - identifier: str | None = None, + identifier: str|None = None, **keywords): super().__init__() - self._identifier: str | None = None + self._identifier: str|None = None self._number: int = 1 self._text: str = '' self._syllabic: SyllabicChoices = None - self.components: list[Lyric] | None = None + self.components: list[Lyric]|None = None self.elisionBefore = ' ' # these are set by setTextAndSyllabic @@ -356,7 +356,7 @@ def syllabic(self, newSyllabic: SyllabicChoices): self._syllabic = newSyllabic @property - def identifier(self) -> str | int: + def identifier(self) -> str|int: ''' By default, this is the same as self.number. However, if there is a descriptive identifier like 'part2verse1', it is stored here and @@ -384,7 +384,7 @@ def identifier(self) -> str | int: return self._identifier @identifier.setter - def identifier(self, value: str | None): + def identifier(self, value: str|None): self._identifier = value @property @@ -602,8 +602,8 @@ class GeneralNote(base.Music21Object): def __init__(self, *, - duration: Duration | None = None, - lyric: None | str | Lyric = None, + duration: Duration|None = None, + lyric: None|str|Lyric = None, **keywords ): if duration is None: @@ -635,7 +635,7 @@ def __init__(self, self.addLyric(lyric) # note: Chords handle ties differently - self._tie: tie.Tie | None = None # store a Tie object + self._tie: tie.Tie|None = None # store a Tie object def __eq__(self, other): if not super().__eq__(other): @@ -662,7 +662,7 @@ def __hash__(self): # -------------------------------------------------------------------------- @property - def tie(self) -> tie.Tie | None: + def tie(self) -> tie.Tie|None: ''' Return and set a :class:`~music21.note.Tie` object, or None. @@ -674,17 +674,17 @@ def tie(self) -> tie.Tie | None: return self._tie @tie.setter - def tie(self, value: tie.Tie | None): + def tie(self, value: tie.Tie|None): self._tie = value - def _getLyric(self) -> str | None: + def _getLyric(self) -> str|None: if not self.lyrics: return None allText = [ly.text for ly in self.lyrics] return '\n'.join([textStr for textStr in allText if textStr is not None]) - def _setLyric(self, value: str | Lyric | None) -> None: + def _setLyric(self, value: str|Lyric|None) -> None: self.lyrics = [] if value is None: return @@ -1012,29 +1012,29 @@ class NotRest(GeneralNote): ) def __init__(self, - beams: beam.Beams | None = None, + beams: beam.Beams|None = None, **keywords): super().__init__(**keywords) self._notehead: str = 'normal' - self._noteheadFill: bool | None = None + self._noteheadFill: bool|None = None self._noteheadParenthesis: bool = False self._stemDirection: str = 'unspecified' - self._volume: volume.Volume | None = None # created on demand + self._volume: volume.Volume|None = None # created on demand if beams is not None: self.beams = beams else: self.beams = beam.Beams() - self._storedInstrument: instrument.Instrument | None = None - self._chordAttached: chord.ChordBase | None = None + self._storedInstrument: instrument.Instrument|None = None + self._chordAttached: chord.ChordBase|None = None # ============================================================================================== # Special functions # ============================================================================================== def _deepcopySubclassable(self: _NotRestType, - memo: dict[int, t.Any] | None = None, + memo: dict[int, t.Any]|None = None, *, - ignoreAttributes: set[str] | None = None) -> _NotRestType: + ignoreAttributes: set[str]|None = None) -> _NotRestType: new = super()._deepcopySubclassable(memo, ignoreAttributes={'_chordAttached'}) if t.TYPE_CHECKING: new = t.cast(_NotRestType, new) @@ -1145,7 +1145,7 @@ def notehead(self, value): self._notehead = value @property - def noteheadFill(self) -> bool | None: + def noteheadFill(self) -> bool|None: ''' Get or set the note head fill status of this NotRest. Valid note head fill values are True, False, or None (meaning default). "yes" and "no" are converted to True @@ -1166,8 +1166,8 @@ def noteheadFill(self) -> bool | None: return self._noteheadFill @noteheadFill.setter - def noteheadFill(self, value: bool | None | str): - boolValue: bool | None + def noteheadFill(self, value: bool|None|str): + boolValue: bool|None if value in ('none', None, 'default'): boolValue = None # allow setting to none or None elif value in (True, 'filled', 'yes'): @@ -1205,7 +1205,7 @@ def noteheadParenthesis(self) -> bool: return self._noteheadParenthesis @noteheadParenthesis.setter - def noteheadParenthesis(self, value: bool | str | int): + def noteheadParenthesis(self, value: bool|str|int): boolValue: bool if value in (True, 'yes', 1): boolValue = True @@ -1236,7 +1236,7 @@ def hasVolumeInformation(self) -> bool: return True def _getVolume(self, - forceClient: NotRest | None = None + forceClient: NotRest|None = None ) -> volume.Volume: # DO NOT CHANGE TO @property because of optional attributes # lazy volume creation. property is set below. @@ -1253,7 +1253,7 @@ def _getVolume(self, return volume_out - def _setVolume(self, value: None | volume.Volume | int | float, setClient=True): + def _setVolume(self, value: None|volume.Volume|int|float, setClient=True): # DO NOT CHANGE TO @property because of optional attributes # setClient is only False when Chords are bundling Notes. if value is None: @@ -1294,7 +1294,7 @@ def volume(self) -> volume.Volume: return self._getVolume() @volume.setter - def volume(self, value: None | volume.Volume | int | float): + def volume(self, value: None|volume.Volume|int|float): self._setVolume(value) def _getStoredInstrument(self): @@ -1328,13 +1328,13 @@ def getInstrument(self, def getInstrument(self, *, returnDefault: t.Literal[False] - ) -> instrument.Instrument | None: + ) -> instrument.Instrument|None: return None # astroid #1015 def getInstrument(self, *, returnDefault: bool = True - ) -> instrument.Instrument | None: + ) -> instrument.Instrument|None: ''' Retrieves the `.storedInstrument` on this `NotRest` instance, if any. If one is not found, executes a context search (without following @@ -1528,13 +1528,13 @@ class Note(NotRest): # Accepts an argument for pitch def __init__(self, - pitch: str | int | Pitch | None = None, + pitch: str|int|Pitch|None = None, *, - name: str | None = None, - nameWithOctave: str | None = None, + name: str|None = None, + nameWithOctave: str|None = None, **keywords): super().__init__(**keywords) - self._chordAttached: chord.Chord | None + self._chordAttached: chord.Chord|None if pitch is not None: if isinstance(pitch, Pitch): @@ -1634,10 +1634,10 @@ def step(self) -> StepName: def step(self, value: StepName): self.pitch.step = value - def _getOctave(self) -> int | None: + def _getOctave(self) -> int|None: return self.pitch.octave - def _setOctave(self, value: int | None): + def _setOctave(self, value: int|None): self.pitch.octave = value octave = property(_getOctave, @@ -1839,11 +1839,11 @@ class Unpitched(NotRest): def __init__( self, - displayName: str | None = None, + displayName: str|None = None, **keywords ): super().__init__(**keywords) - self._chordAttached: percussion.PercussionChord | None = None + self._chordAttached: percussion.PercussionChord|None = None self.displayStep: StepName = 'B' self.displayOctave: int = 4 @@ -1983,7 +1983,7 @@ class Rest(GeneralNote): } def __init__(self, - length: str | OffsetQLIn | None = None, + length: str|OffsetQLIn|None = None, *, stepShift: int = 0, fullMeasure: t.Literal[True, False, 'auto', 'always'] = 'auto', diff --git a/music21/noteworthy/binaryTranslate.py b/music21/noteworthy/binaryTranslate.py index 6dc9df7e32..228fd2dd8d 100644 --- a/music21/noteworthy/binaryTranslate.py +++ b/music21/noteworthy/binaryTranslate.py @@ -265,7 +265,7 @@ def __init__(self, **keywords) -> None: self.currentAlterations: dict[int, str] = {} # noinspection SpellCheckingInspection - def parseFile(self, fp: pathlib.Path | str): + def parseFile(self, fp: pathlib.Path|str): # noinspection PyShadowingNames r''' Parse a file (calls .toStream) diff --git a/music21/percussion.py b/music21/percussion.py index 84e350e370..b1198d0e9d 100644 --- a/music21/percussion.py +++ b/music21/percussion.py @@ -102,7 +102,7 @@ def notes(self) -> tuple[note.NotRest, ...]: return tuple(self._notes) @notes.setter - def notes(self, newNotes: Iterable[note.Unpitched | note.Note]) -> None: + def notes(self, newNotes: Iterable[note.Unpitched|note.Note]) -> None: ''' Sets notes to an iterable of Note or Unpitched objects ''' @@ -154,7 +154,7 @@ def pitches(self) -> tuple[pitch.Pitch, ...]: return pitches @pitches.setter - def pitches(self, value: t.Sequence[str | pitch.Pitch | int]): + def pitches(self, value: t.Sequence[str|pitch.Pitch|int]): self._notes = [] # TODO: individual ties are not being retained here for p in value: diff --git a/music21/pitch.py b/music21/pitch.py index e28fb8fd90..e998751426 100644 --- a/music21/pitch.py +++ b/music21/pitch.py @@ -240,8 +240,8 @@ def standardizeAccidentalName(name: str) -> str: # utility functions def _convertPitchClassToNumber( - ps: int | float | PitchClassString -) -> int | float: + ps: int|float|PitchClassString +) -> int|float: ''' Given a pitch class string return the pitch class representation. @@ -283,7 +283,7 @@ def convertPitchClassToStr(pc: int) -> str: return f'{pc:X}' # using hex conversion, good up to 15 -def _convertPsToOct(ps: int | float) -> int: +def _convertPsToOct(ps: int|float) -> int: ''' Utility conversion; does not process internals. Converts a midiNote number to an octave number. @@ -312,7 +312,7 @@ def _convertPsToOct(ps: int | float) -> int: def _convertPsToStep( - ps: int | float + ps: int|float ) -> tuple[StepName, Accidental, Microtone, @@ -512,7 +512,7 @@ def _convertCentsToAlterAndCents(shift) -> tuple[float, float]: return alterShift + alterAdd, float(cents) -def _convertHarmonicToCents(value: int | float) -> int: +def _convertHarmonicToCents(value: int|float) -> int: r''' Given a harmonic number, return the total number shift in cents assuming 12 tone equal temperament. @@ -787,9 +787,9 @@ class Microtone(prebase.ProtoM21Object, SlottedObjectMixin): # INITIALIZER # def __init__(self, - centsOrString: str | int | float = 0, + centsOrString: str|int|float = 0, harmonicShift=1): - self._centShift: int | float = 0 + self._centShift: int|float = 0 self._harmonicShift: int = harmonicShift # the first harmonic is the start if isinstance(centsOrString, (int, float)): @@ -987,7 +987,7 @@ class Accidental(prebase.ProtoM21Object, style.StyleMixin): # INITIALIZER # - def __init__(self, specifier: int | str | float = 'natural'): + def __init__(self, specifier: int|str|float = 'natural'): super().__init__() # managed by properties self._displayType = 'normal' @@ -1003,7 +1003,7 @@ def __init__(self, specifier: int | str | float = 'natural'): self.displayLocation = 'normal' # store a reference to the Pitch that has this Accidental object as a property - self._client: Pitch | None = None + self._client: Pitch|None = None self._name = '' self._modifier = '' self._alter = 0.0 # semitones to alter step @@ -1901,19 +1901,19 @@ class Pitch(prebase.ProtoM21Object): } def __init__(self, - name: str | int | float | None = None, + name: str|int|float|None = None, *, - step: StepName | None = None, - octave: int | None = None, - accidental: Accidental | str | int | float | None = None, - microtone: Microtone | int | float | None = None, - pitchClass: int | PitchClassString | None = None, - midi: int | None = None, - ps: float | None = None, - fundamental: Pitch | None = None, + step: StepName|None = None, + octave: int|None = None, + accidental: Accidental|str|int|float|None = None, + microtone: Microtone|int|float|None = None, + pitchClass: int|PitchClassString|None = None, + midi: int|None = None, + ps: float|None = None, + fundamental: Pitch|None = None, **keywords): # No need for super().__init__() on protoM21Object - self._groups: base.Groups | None = None + self._groups: base.Groups|None = None if isinstance(name, type(self)): name = name.nameWithOctave @@ -1921,14 +1921,14 @@ def __init__(self, # this should not be set, as will be updated when needed self._step: StepName = defaults.pitchStep # this is only the pitch step - self._overridden_freq440: float | None = None + self._overridden_freq440: float|None = None # store an Accidental and Microtone objects # note that creating an Accidental object is much more time-consuming # than a microtone - self._accidental: Accidental | None = None + self._accidental: Accidental|None = None # 5% of pitch creation time; it'll be created in a sec anyhow - self._microtone: Microtone | None = None + self._microtone: Microtone|None = None # # CA, Q: should this remain an attribute or only refer to value in defaults? # # MSC A: no, it's a useful attribute for cases such as scales where if there are @@ -1936,17 +1936,17 @@ def __init__(self, # # MSC 12 years later: maybe Chris was right... # self.defaultOctave: int = defaults.pitchOctave # # MSC: even later: Chris Ariza was right - self._octave: int | None = None + self._octave: int|None = None # if True, accidental is not known; is determined algorithmically # likely due to pitch data from midi or pitch space/class numbers self.spellingIsInferred = False # the fundamental attribute stores an optional pitch # that defines the fundamental used to create this Pitch - self.fundamental: Pitch | None = None + self.fundamental: Pitch|None = None # so that we can tell clients about changes in pitches. - self._client: note.Note | None = None + self._client: note.Note|None = None # name combines step, octave, and accidental if name is not None: @@ -2189,7 +2189,7 @@ def groups(self, new: base.Groups): self._groups = new @property - def accidental(self) -> Accidental | None: + def accidental(self) -> Accidental|None: ''' Stores an optional accidental object contained within the Pitch object. This might return None, which is different @@ -2213,7 +2213,7 @@ def accidental(self) -> Accidental | None: return self._accidental @accidental.setter - def accidental(self, value: str | Accidental | None | int | float): + def accidental(self, value: str|Accidental|None|int|float): if isinstance(value, Accidental): self._accidental = value elif value is None: @@ -2269,7 +2269,7 @@ def microtone(self) -> Microtone: return self._microtone @microtone.setter - def microtone(self, value: float | int | str | None | Microtone): + def microtone(self, value: float|int|str|None|Microtone): if isinstance(value, (str, float, int)): self._microtone = Microtone(value) elif value is None: # set to zero @@ -3115,9 +3115,9 @@ def pitchClass(self) -> int: return round(self.ps) % 12 @pitchClass.setter - def pitchClass(self, value: int | PitchClassString): + def pitchClass(self, value: int|PitchClassString): # permit the submission of strings, like "A" and "B" - valueOut: int | float = _convertPitchClassToNumber(value) + valueOut: int|float = _convertPitchClassToNumber(value) # get step and accidental w/o octave self.step, self._accidental = _convertPsToStep(valueOut)[0:2] @@ -3154,7 +3154,7 @@ def pitchClassString(self, v): @property - def octave(self) -> int | None: + def octave(self) -> int|None: ''' Returns or sets the octave of the note. Setting the octave updates the pitchSpace attribute. @@ -3182,7 +3182,7 @@ def octave(self) -> int | None: return self._octave @octave.setter - def octave(self, value: int | float | None): + def octave(self, value: int|float|None): if value is not None: self._octave = int(value) else: @@ -3510,7 +3510,7 @@ def frequency(self) -> float: return self.freq440 @frequency.setter - def frequency(self, value: int | float): + def frequency(self, value: int|float): self.freq440 = value # these methods may belong in a temperament object @@ -3538,7 +3538,7 @@ def freq440(self) -> float: return 440.0 * (self._twelfth_root_of_two ** A4offset) @freq440.setter - def freq440(self, value: int | float): + def freq440(self, value: int|float): post = 12 * (math.log(value / 440.0) / math.log(2)) + 69 # environLocal.printDebug(['convertFqToPs():', 'input', fq, 'output', repr(post)]) # rounding here is essential @@ -3647,7 +3647,7 @@ def getHarmonic(self, number: int) -> Pitch: return final def harmonicFromFundamental(self, - fundamental: str | Pitch, + fundamental: str|Pitch, ) -> tuple[int, float]: # noinspection PyShadowingNames ''' @@ -3765,7 +3765,7 @@ def harmonicFromFundamental(self, # return harmonicMatch, fundamental def harmonicString(self, - fundamental: str | Pitch | None = None + fundamental: str|Pitch|None = None ) -> str: ''' Return a string representation of a harmonic equivalence. @@ -3827,7 +3827,7 @@ def harmonicString(self, def harmonicAndFundamentalFromPitch( self, - target: str | Pitch + target: str|Pitch ) -> tuple[int, Pitch]: ''' Given a Pitch that is a plausible target for a fundamental, @@ -3860,7 +3860,7 @@ def harmonicAndFundamentalFromPitch( def harmonicAndFundamentalStringFromPitch( self, - fundamental: str | Pitch + fundamental: str|Pitch ) -> str: ''' Given a Pitch that is a plausible target for a fundamental, @@ -4025,7 +4025,7 @@ def _getEnharmonicHelper(self: PitchType, def _getEnharmonicHelper(self: PitchType, inPlace: bool, - up: bool) -> PitchType | None: + up: bool) -> PitchType|None: ''' abstracts the code from `getHigherEnharmonic` and `getLowerEnharmonic` ''' @@ -4061,7 +4061,7 @@ def getHigherEnharmonic(self: PitchType, *, inPlace: t.Literal[False]) -> PitchT def getHigherEnharmonic(self: PitchType, *, inPlace: t.Literal[True]) -> None: return None - def getHigherEnharmonic(self: PitchType, *, inPlace: bool = False) -> PitchType | None: + def getHigherEnharmonic(self: PitchType, *, inPlace: bool = False) -> PitchType|None: ''' Returns an enharmonic `Pitch` object that is a higher enharmonic. That is, the `Pitch` a diminished-second above @@ -4125,7 +4125,7 @@ def getLowerEnharmonic(self: PitchType, *, inPlace: t.Literal[False]) -> PitchTy def getLowerEnharmonic(self: PitchType, *, inPlace: t.Literal[True]) -> None: return None - def getLowerEnharmonic(self: PitchType, *, inPlace: bool = False) -> PitchType | None: + def getLowerEnharmonic(self: PitchType, *, inPlace: bool = False) -> PitchType|None: ''' returns a Pitch enharmonic that is a diminished second below the current note @@ -4163,7 +4163,7 @@ def simplifyEnharmonic( *, inPlace=False, mostCommon=False - ) -> PitchType | None: + ) -> PitchType|None: ''' Returns a new Pitch (or sets the current one if inPlace is True) that is either the same as the current pitch or has fewer @@ -4252,7 +4252,7 @@ def simplifyEnharmonic( else: return returnObj - def getEnharmonic(self: PitchType, *, inPlace=False) -> PitchType | None: + def getEnharmonic(self: PitchType, *, inPlace=False) -> PitchType|None: ''' Returns a new Pitch that is the(/an) enharmonic equivalent of this Pitch. Can be thought of as flipEnharmonic or something like that. @@ -4510,7 +4510,7 @@ def diatonicNoteNum(self, newNum: int): @overload def transpose( self: PitchType, - value: interval.IntervalBase | str | int, + value: interval.IntervalBase|str|int, *, inPlace: t.Literal[True] ) -> None: @@ -4519,7 +4519,7 @@ def transpose( @overload def transpose( self: PitchType, - value: interval.IntervalBase | str | int, + value: interval.IntervalBase|str|int, *, inPlace: t.Literal[False] = False ) -> PitchType: @@ -4527,10 +4527,10 @@ def transpose( def transpose( self: PitchType, - value: interval.IntervalBase | str | int, + value: interval.IntervalBase|str|int, *, inPlace: bool = False - ) -> PitchType | None: + ) -> PitchType|None: ''' Transpose the pitch by the user-provided value. If the value is an integer, the transposition is treated in half steps. If the value is a @@ -4665,7 +4665,7 @@ def transposeBelowTarget( *, minimize=False, inPlace=False - ) -> PitchType | None: + ) -> PitchType|None: # noinspection PyShadowingNames ''' Given a source Pitch, shift it down some number of octaves until it is below the @@ -4763,7 +4763,7 @@ def transposeAboveTarget(self: PitchType, target, *, minimize=False, - inPlace=False) -> PitchType | None: + inPlace=False) -> PitchType|None: ''' Given a source Pitch, shift it up octaves until it is above the target. @@ -4917,10 +4917,10 @@ def _stepInKeySignature(self, alteredPitches): def updateAccidentalDisplay( self, *, - pitchPast: list[Pitch] | None = None, - pitchPastMeasure: list[Pitch] | None = None, - otherSimultaneousPitches: list[Pitch] | None = None, - alteredPitches: list[Pitch] | None = None, + pitchPast: list[Pitch]|None = None, + pitchPastMeasure: list[Pitch]|None = None, + otherSimultaneousPitches: list[Pitch]|None = None, + alteredPitches: list[Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, diff --git a/music21/prebase.py b/music21/prebase.py index 329ec438a1..b49e085eed 100644 --- a/music21/prebase.py +++ b/music21/prebase.py @@ -78,7 +78,7 @@ class ProtoM21Object: # it only needs to be made once (11 microseconds per call, can be # a big part of iteration; from cache just 1 microsecond) _classTupleCacheDict: dict[type, tuple[str, ...]] = {} - _classSetCacheDict: dict[type, frozenset[str | type]] = {} + _classSetCacheDict: dict[type, frozenset[str|type]] = {} __slots__: tuple[str, ...] = () @@ -160,7 +160,7 @@ def classes(self) -> tuple[str, ...]: return classTuple @property - def classSet(self) -> frozenset[str | type]: + def classSet(self) -> frozenset[str|type]: ''' Returns a set (that is, unordered, but indexed) of all classes that this class belongs to, including @@ -223,7 +223,7 @@ def classSet(self) -> frozenset[str | type]: try: return self._classSetCacheDict[self.__class__] except KeyError: - classList: list[str | type] = list(self.classes) + classList: list[str|type] = list(self.classes) classList.extend(self.__class__.mro()) fullyQualifiedStrings = [x.__module__ + '.' + x.__name__ for x in self.__class__.mro()] classList.extend(fullyQualifiedStrings) diff --git a/music21/repeat.py b/music21/repeat.py index 18d3e5ee07..8569f8c037 100644 --- a/music21/repeat.py +++ b/music21/repeat.py @@ -1739,7 +1739,7 @@ def getRepeatExpressionIndex(self, streamObj, target): return post return None - def isExpandable(self) -> bool | None: + def isExpandable(self) -> bool|None: ''' Return True or False if this Stream is expandable, that is, if it has balanced repeats or sensible Da Capo or Dal Segno diff --git a/music21/roman.py b/music21/roman.py index ecb8ba47c6..e53c1ad07d 100644 --- a/music21/roman.py +++ b/music21/roman.py @@ -526,9 +526,9 @@ def figureTupleSolo( def identifyAsTonicOrDominant( - inChord: list | tuple | chord.Chord, + inChord: list|tuple|chord.Chord, inKey: key.Key -) -> str | t.Literal[False]: +) -> str|t.Literal[False]: ''' Returns the roman numeral string expression (either tonic or dominant) that best matches the inChord. Useful when you know inChord is either tonic or @@ -607,7 +607,7 @@ def identifyAsTonicOrDominant( return rootScaleDeg + romanInversionName(inChord) -def romanInversionName(inChord: chord.Chord, inv: int | None = None) -> str: +def romanInversionName(inChord: chord.Chord, inv: int|None = None) -> str: ''' Extremely similar to Chord's inversionName() method, but returns string values and allows incomplete triads. @@ -738,7 +738,7 @@ def correctRNAlterationForMinor( def romanNumeralFromChord( chordObj: chord.Chord, - keyObj: key.Key | str | None = None, + keyObj: key.Key|str|None = None, preferSecondaryDominants: bool = False, ) -> RomanNumeral: # noinspection PyShadowingNames @@ -2380,8 +2380,8 @@ class RomanNumeral(harmony.Harmony): def __init__( self, - figure: str | int = '', - keyOrScale: key.Key | scale.ConcreteScale | str | None = None, + figure: str|int = '', + keyOrScale: key.Key|scale.ConcreteScale|str|None = None, *, caseMatters=True, updatePitches=True, @@ -2390,10 +2390,10 @@ def __init__( **keywords, ): self.primaryFigure: str = '' - self.secondaryRomanNumeral: RomanNumeral | None = None - self.secondaryRomanNumeralKey: key.Key | None = None + self.secondaryRomanNumeral: RomanNumeral|None = None + self.secondaryRomanNumeralKey: key.Key|None = None - self.pivotChord: RomanNumeral | None = None + self.pivotChord: RomanNumeral|None = None self.caseMatters: bool = caseMatters self.scaleCardinality: int = 7 @@ -2434,8 +2434,8 @@ def __init__( self._scale = None self.scaleDegree: int = 0 self.frontAlterationString: str = '' - self.frontAlterationTransposeInterval: interval.Interval | None = None - self.frontAlterationAccidental: pitch.Accidental | None = None + self.frontAlterationTransposeInterval: interval.Interval|None = None + self.frontAlterationAccidental: pitch.Accidental|None = None self.romanNumeralAlone: str = '' self.figuresWritten: str = '' self.figuresNotationObj: fbNotation.Notation = _NOTATION_SINGLETON @@ -2444,7 +2444,7 @@ def __init__( self.impliedQuality: str = '' - self.impliedScale: scale.ConcreteScale | None = None + self.impliedScale: scale.ConcreteScale|None = None self.useImpliedScale: bool = False self.bracketedAlterations: list[tuple[str, int]] = [] self.omittedSteps: list[int] = [] @@ -2458,7 +2458,7 @@ def __init__( super().__init__(figure, updatePitches=updatePitches, **keywords) self.writeAsChord = True # override from Harmony/ChordSymbol self._parsingComplete = True - self._functionalityScore: int | None = None + self._functionalityScore: int|None = None self.followsKeyChange: bool = False def __eq__(self, other): @@ -2727,9 +2727,9 @@ def shouldSkipThisChordStep(chordStep: int) -> bool: def _correctForSecondaryRomanNumeral( self, - useScale: key.Key | scale.ConcreteScale, - figure: str | None = None - ) -> tuple[str, key.Key | scale.ConcreteScale]: + useScale: key.Key|scale.ConcreteScale, + figure: str|None = None + ) -> tuple[str, key.Key|scale.ConcreteScale]: ''' Creates .secondaryRomanNumeral object and .secondaryRomanNumeralKey Key object inside the RomanNumeral object (recursively in case of V/V/V/V etc.) and returns @@ -2941,8 +2941,8 @@ def _parseFrontAlterations(self, workingFigure: str) -> str: def _parseRNAloneAmidstAug6( self, workingFigure: str, - useScale: key.Key | scale.ConcreteScale, - ) -> tuple[str, key.Key | scale.ConcreteScale]: + useScale: key.Key|scale.ConcreteScale, + ) -> tuple[str, key.Key|scale.ConcreteScale]: # noinspection PyShadowingNames ''' Sets and removes from workingFigure the roman numeral alone, possibly @@ -3049,7 +3049,7 @@ def _parseRNAloneAmidstAug6( def adjustMinorVIandVIIByQuality( self, - useScale: key.Key | scale.ConcreteScale + useScale: key.Key|scale.ConcreteScale ) -> None: ''' Fix minor vi and vii to always be #vi and #vii if `.caseMatters`. @@ -3081,7 +3081,7 @@ def adjustMinorVIandVIIByQuality( def _adjustMinorVIandVIIByQuality( self, workingFigure: str, - useScale: key.Key | scale.ConcreteScale + useScale: key.Key|scale.ConcreteScale ) -> str: ''' Fix minor vi and vii to always be #vi and #vii if `.caseMatters`. @@ -3193,7 +3193,7 @@ def _updatePitches(self) -> None: ''' Utility function to update the pitches to the new figure etc. ''' - useScale: key.Key | scale.ConcreteScale + useScale: key.Key|scale.ConcreteScale if self.secondaryRomanNumeralKey is not None: useScale = self.secondaryRomanNumeralKey elif self.useImpliedScale and self.impliedScale is not None: @@ -3303,7 +3303,7 @@ def _updatePitches(self) -> None: f'_updatePitches() was unable to derive pitches from the figure: {self.figure!r}' ) # pragma: no cover - def transpose(self: T, value, *, inPlace=False) -> T | None: + def transpose(self: T, value, *, inPlace=False) -> T|None: ''' Overrides :meth:`~music21.harmony.Harmony.transpose` so that `key` attribute is transposed as well. @@ -3522,7 +3522,7 @@ def key(self, keyOrScale): # ]) @property - def scaleDegreeWithAlteration(self) -> tuple[int, pitch.Accidental | None]: + def scaleDegreeWithAlteration(self) -> tuple[int, pitch.Accidental|None]: ''' Returns a two element tuple of the scale degree and the accidental that alters the scale degree for things such as #ii or @@ -3546,7 +3546,7 @@ def scaleDegreeWithAlteration(self) -> tuple[int, pitch.Accidental | None]: def bassScaleDegreeFromNotation( self, - notationObject: fbNotation.Notation | None = None + notationObject: fbNotation.Notation|None = None ) -> int: ''' Given a notationObject from diff --git a/music21/romanText/clercqTemperley.py b/music21/romanText/clercqTemperley.py index 9a3598d543..139b388e6a 100644 --- a/music21/romanText/clercqTemperley.py +++ b/music21/romanText/clercqTemperley.py @@ -337,7 +337,7 @@ class CTSong(prebase.ProtoM21Object): ''', } - def __init__(self, textFile: str | pathlib.Path = '', **keywords): + def __init__(self, textFile: str|pathlib.Path = '', **keywords): self._title = None self.text = '' self.lines: list[str] = [] @@ -369,7 +369,7 @@ def _reprInternal(self): return f'title={self.title!r} year={self.year}' # -------------------------------------------------------------------------- - def parse(self, textFile: str | pathlib.Path): + def parse(self, textFile: str|pathlib.Path): ''' Called when a CTSong is created by passing a string or filename; in the second case, it opens the file @@ -648,7 +648,7 @@ class CTRule(prebase.ProtoM21Object): SPLITMEASURES = re.compile(r'(\|\*?\d*)') REPETITION = re.compile(r'\*(\d+)') - def __init__(self, text='', parent: CTSong | None = None): + def __init__(self, text='', parent: CTSong|None = None): self._parent = None if parent is not None: self.parent = parent @@ -662,7 +662,7 @@ def __init__(self, text='', parent: CTSong | None = None): self.measures: list[stream.Measure] = [] self.lastRegularAtom: str = '' - self.lastChord: chord.Chord | None = None + self.lastChord: chord.Chord|None = None self._lastChordIsInSameMeasure: bool = False @@ -683,8 +683,8 @@ def _setParent(self, parent): def expand( self, - tsContext: meter.TimeSignature | None = None, - keyContext: key.Key | None = None, + tsContext: meter.TimeSignature|None = None, + keyContext: key.Key|None = None, ) -> list[stream.Measure]: ''' The meat of it all -- expand one rule completely and return a list of Measure objects. @@ -923,7 +923,7 @@ def _measureGroups(self) -> list[tuple[str, str, int]]: return measureGroups3 # -------------------------------------------------------------------------- - def isSame(self, rn: roman.RomanNumeral, lastChord: chord.Chord | None) -> bool: + def isSame(self, rn: roman.RomanNumeral, lastChord: chord.Chord|None) -> bool: ''' Returns True if the pitches of the RomanNumeral are the same as the pitches of lastChord. Returns False if lastChord is None. @@ -942,7 +942,7 @@ def isSame(self, rn: roman.RomanNumeral, lastChord: chord.Chord | None) -> bool: def addOptionalTieAndLyrics( self, rn: roman.RomanNumeral, - lastChord: chord.Chord | None + lastChord: chord.Chord|None ) -> None: ''' Adds ties to chords that are the same. Adds lyrics to chords that change. @@ -1035,7 +1035,7 @@ def _getMusicText(self): ''') @property - def comment(self) -> str | None: + def comment(self) -> str|None: ''' Get the comment of a CTRule object. diff --git a/music21/romanText/translate.py b/music21/romanText/translate.py index 610deef066..0408fe4ee0 100644 --- a/music21/romanText/translate.py +++ b/music21/romanText/translate.py @@ -231,7 +231,7 @@ def _copySingleMeasure(rtTagged, p, kCurrent): def _copyMultipleMeasures(rtMeasure: rtObjects.RTMeasure, p: stream.Part, - kCurrent: key.Key | None): + kCurrent: key.Key|None): ''' Given a RomanText token for a RTMeasure, a Part used as the current container, and the current Key, @@ -1759,7 +1759,7 @@ def _test_ending_contents( rn_iter = measure[roman.RomanNumeral] self.assertEqual(len(rn_iter), 1) # mypy complains about the next line because - # RecursiveIterator.first() has X | None type, but we know + # RecursiveIterator.first() has X|None type, but we know # it will not be None because we have just asserted that rn_iter # has length 1 self.assertEqual(rn_iter.first().figure, 'I') # type: ignore diff --git a/music21/romanText/tsvConverter.py b/music21/romanText/tsvConverter.py index ee873642a4..20414e01d3 100644 --- a/music21/romanText/tsvConverter.py +++ b/music21/romanText/tsvConverter.py @@ -164,19 +164,19 @@ class TabChordBase(abc.ABC): def __init__(self) -> None: super().__init__() self.numeral: str = '' - self.relativeroot: str | None = None - self.representationType: str | None = None # Added (not in DCML) + self.relativeroot: str|None = None + self.representationType: str|None = None # Added (not in DCML) self.extra: dict[str, str] = {} self.dcml_version = -1 # shared between DCML v1 and v2 self.chord: str = '' self.timesig: str = '' - self.pedal: str | None = None - self.form: str | None = None - self.figbass: str | None = None - self.changes: str | None = None - self.phraseend: str | None = None + self.pedal: str|None = None + self.form: str|None = None + self.figbass: str|None = None + self.changes: str|None = None + self.phraseend: str|None = None # the following attributes are overwritten by properties in TabChordV2 # because of changed column names in DCML v2 @@ -401,9 +401,9 @@ class TabChord(TabChordBase): def __init__(self) -> None: # self.numeral and self.relativeroot defined in super().__init__() super().__init__() - self.altchord: str | None = None - self.totbeat: str | None = None - self.length: fractions.Fraction | float | None = None + self.altchord: str|None = None + self.totbeat: str|None = None + self.length: fractions.Fraction|float|None = None self.dcml_version: int = 1 class TabChordV2(TabChordBase): @@ -532,8 +532,8 @@ def __init__(self, tsvFile: str, dcml_version: int = 1): raise ValueError(f'dcml_version {dcml_version} is not in (1, 2)') self.tsvFileName = tsvFile self.chordList: list[TabChordBase] = [] - self.m21stream: stream.Score | None = None - self._head_indices: dict[str, tuple[int, type | t.Any]] = {} + self.m21stream: stream.Score|None = None + self._head_indices: dict[str, tuple[int, type|t.Any]] = {} self._extra_indices: dict[int, str] = {} self.dcml_version = dcml_version self.tsvData = self._importTsv() # converted to private @@ -618,7 +618,7 @@ def toM21Stream(self) -> stream.Score: for thisChord in self.chordList: offsetInMeasure = thisChord.beat - 1 # beats always measured in quarter notes if isinstance(thisChord, TabChordV2) and thisChord.volta: - measureNumber: str | int = ( + measureNumber: str|int = ( f'{thisChord.measure}{string.ascii_lowercase[int(thisChord.volta) - 1]}' ) else: @@ -680,7 +680,7 @@ def prepStream(self) -> stream.Score: currentMeasureLength = ts.barDuration.quarterLength - currentOffset: float | fractions.Fraction = 0.0 + currentOffset: float|fractions.Fraction = 0.0 previousMeasure: int = self.chordList[0].measure - 1 # Covers pickups previousVolta: str = '' @@ -715,7 +715,7 @@ def prepStream(self) -> stream.Score: previousMeasure = mNo else: # entry.measure <= previousMeasure + 1 if isinstance(entry, TabChordV2) and entry.volta: - measureNumber: str | int = ( + measureNumber: str|int = ( f'{entry.measure}{string.ascii_lowercase[int(entry.volta) - 1]}' ) else: diff --git a/music21/romanText/writeRoman.py b/music21/romanText/writeRoman.py index b4f5017ac4..839eab2bca 100644 --- a/music21/romanText/writeRoman.py +++ b/music21/romanText/writeRoman.py @@ -127,7 +127,7 @@ def __init__(self, self.analyst = '' self.proofreader = '' self.combinedList: list[str] = [] - self.container: stream.Part | stream.Score + self.container: stream.Part|stream.Score if isinstance(obj, stream.Stream): if isinstance(obj, stream.Opus): @@ -180,7 +180,7 @@ def __init__(self, self.prepSequentialListOfLines() def _makeContainer(self, - obj: stream.Stream | list): + obj: stream.Stream|list): ''' Makes a placeholder container for the unusual cases where this class is called on generic- or non-stream object as opposed to @@ -363,10 +363,10 @@ def getChordString(self, # ------------------------------------------------------------------------------ -def rnString(measureNumber: int | str, - beat: str | int | float | fractions.Fraction, +def rnString(measureNumber: int|str, + beat: str|int|float|fractions.Fraction, chordString: str, - inString: str | None = ''): + inString: str|None = ''): ''' Creates or extends a string of RomanText such that the output corresponds to a single measure line. @@ -413,7 +413,7 @@ def rnString(measureNumber: int | str, return newString -def intBeat(beat: str | int | float | fractions.Fraction, +def intBeat(beat: str|int|float|fractions.Fraction, roundValue: int = 2): ''' Converts beats to integers if possible, and otherwise to rounded decimals. diff --git a/music21/scale/__init__.py b/music21/scale/__init__.py index 3f393155e3..fb9c963700 100644 --- a/music21/scale/__init__.py +++ b/music21/scale/__init__.py @@ -568,7 +568,7 @@ def nextPitch(self, pitchOrigin, direction: Direction = Direction.ASCENDING, stepSize=1, - getNeighbor: Direction | bool = True): + getNeighbor: Direction|bool = True): ''' Expose functionality from :class:`~music21.intervalNetwork.IntervalNetwork`, passing on the stored alteredDegrees dictionary. @@ -686,7 +686,7 @@ class AbstractDiatonicScale(AbstractScale): >>> as1 == as3 True ''' - def __init__(self, mode: str | None = None, **keywords): + def __init__(self, mode: str|None = None, **keywords): super().__init__(**keywords) self.mode = mode self.type = 'Abstract diatonic' @@ -850,7 +850,7 @@ class AbstractHarmonicMinorScale(AbstractScale): mode is not used ''' - def __init__(self, mode: str | None = None, **keywords) -> None: + def __init__(self, mode: str|None = None, **keywords) -> None: super().__init__(**keywords) self.type = 'Abstract Harmonic Minor' self.octaveDuplicating = True @@ -879,7 +879,7 @@ class AbstractMelodicMinorScale(AbstractScale): mode is not used. ''' - def __init__(self, mode: str | None = None, **keywords) -> None: + def __init__(self, mode: str|None = None, **keywords) -> None: super().__init__(**keywords) self.type = 'Abstract Melodic Minor' self.octaveDuplicating = True @@ -1262,15 +1262,15 @@ class ConcreteScale(Scale): usePitchDegreeCache = False def __init__(self, - tonic: str | pitch.Pitch | note.Note | None = None, - pitches: list[pitch.Pitch | str] | None = None, + tonic: str|pitch.Pitch|note.Note|None = None, + pitches: list[pitch.Pitch|str]|None = None, **keywords): super().__init__(**keywords) self.type = 'Concrete' # store an instance of an abstract scale # subclasses might use multiple abstract scales? - self._abstract: AbstractScale | None = None + self._abstract: AbstractScale|None = None # determine whether this is a limited range self.boundRange = False @@ -1286,7 +1286,7 @@ def __init__(self, # found on # no default tonic is defined; as such, it is mostly an abstract scale, and # can't be used concretely until it is created. - self.tonic: pitch.Pitch | None + self.tonic: pitch.Pitch|None if tonic is None: self.tonic = None # pitch.Pitch() elif isinstance(tonic, str): @@ -1523,7 +1523,7 @@ def tuneOnePitch(p, dst: list[pitch.Pitch]): pDstNew.octave = pEnh.octave # copy octave # need to adjust enharmonic pDstNewEnh = pDstNew.getAllCommonEnharmonics(alterLimit=2) - match: pitch.Pitch | None = None + match: pitch.Pitch|None = None for x in pDstNewEnh: # try to match enharmonic with original alt if x.name == pAlt.name: @@ -1573,9 +1573,9 @@ def romanNumeral(self, degree): def getPitches( self, - minPitch: str | pitch.Pitch | None = None, - maxPitch: str | pitch.Pitch | None = None, - direction: Direction | None = None + minPitch: str|pitch.Pitch|None = None, + maxPitch: str|pitch.Pitch|None = None, + direction: Direction|None = None ) -> list[pitch.Pitch]: ''' Return a list of Pitch objects, using a @@ -1596,13 +1596,13 @@ def getPitches( pitchObj = self.tonic stepOfPitch = self._abstract.tonicDegree - minPitchObj: pitch.Pitch | None + minPitchObj: pitch.Pitch|None if isinstance(minPitch, str): minPitchObj = pitch.Pitch(minPitch) else: minPitchObj = minPitch - maxPitchObj: pitch.Pitch | None + maxPitchObj: pitch.Pitch|None if isinstance(maxPitch, str): maxPitchObj = pitch.Pitch(maxPitch) else: @@ -1700,7 +1700,7 @@ def pitchFromDegree( if self._abstract is None: # pragma: no cover raise ScaleException('Abstract scale underpinning this scale is not defined.') - cacheKey: _PitchDegreeCacheKey | None = None + cacheKey: _PitchDegreeCacheKey|None = None if (self.usePitchDegreeCache and self.tonic and not minPitch and not maxPitch and getattr(self, 'type', None)): tonicCacheKey = self.tonic.nameWithOctave @@ -2055,9 +2055,9 @@ def solfeg(self, def next( self, pitchOrigin=None, - direction: Direction | int = Direction.ASCENDING, + direction: Direction|int = Direction.ASCENDING, stepSize=1, - getNeighbor: Direction | bool = True, + getNeighbor: Direction|bool = True, ): # pragma: no cover ''' See :meth:`~music21.scale.ConcreteScale.nextPitch`. This function @@ -2079,9 +2079,9 @@ def next( def nextPitch( self, pitchOrigin=None, - direction: Direction | int = Direction.ASCENDING, + direction: Direction|int = Direction.ASCENDING, stepSize=1, - getNeighbor: Direction | bool = True, + getNeighbor: Direction|bool = True, ): ''' Get the next pitch above (or below if direction is Direction.DESCENDING) @@ -2173,7 +2173,7 @@ def isNext(self, pitchOrigin, direction: Direction = Direction.ASCENDING, stepSize=1, - getNeighbor: Direction | bool = True, + getNeighbor: Direction|bool = True, comparisonAttribute='name'): ''' Given another pitch, as well as an origin and a direction, @@ -2559,7 +2559,7 @@ class DiatonicScale(ConcreteScale): ''' usePitchDegreeCache = True - def __init__(self, tonic: str | pitch.Pitch | note.Note | None = None, **keywords): + def __init__(self, tonic: str|pitch.Pitch|note.Note|None = None, **keywords): super().__init__(tonic=tonic, **keywords) self._abstract: AbstractDiatonicScale = AbstractDiatonicScale(**keywords) self.type = 'diatonic' @@ -3031,7 +3031,7 @@ class OctaveRepeatingScale(ConcreteScale): [, , ] ''' - def __init__(self, tonic=None, intervalList: list | None = None, **keywords): + def __init__(self, tonic=None, intervalList: list|None = None, **keywords): super().__init__(tonic=tonic, **keywords) mode = intervalList if intervalList else ['m2'] self._abstract = AbstractOctaveRepeatingScale(mode=mode) @@ -3060,8 +3060,8 @@ class CyclicalScale(ConcreteScale): ''' def __init__(self, - tonic: str | pitch.Pitch | note.Note | None = None, - intervalList: list | None = None, + tonic: str|pitch.Pitch|note.Note|None = None, + intervalList: list|None = None, **keywords): super().__init__(tonic=tonic, **keywords) mode = intervalList if intervalList else ['m2'] @@ -3166,7 +3166,7 @@ class SieveScale(ConcreteScale): def __init__(self, tonic=None, sieveString='2@0', - eld: int | float = 1, + eld: int|float = 1, **keywords): super().__init__(tonic=tonic, **keywords) diff --git a/music21/scale/intervalNetwork.py b/music21/scale/intervalNetwork.py index 81d84b08e4..a42b5fac50 100644 --- a/music21/scale/intervalNetwork.py +++ b/music21/scale/intervalNetwork.py @@ -81,7 +81,7 @@ def __str__(self): CacheKey = tuple[ - int | Terminus, str, str | None, str | None, bool, bool | None] + int|Terminus, str, str|None, str|None, bool, bool|None] def _gte(a, b): @@ -153,7 +153,7 @@ class Edge(prebase.ProtoM21Object): # noinspection PyShadowingBuiltins # pylint: disable=redefined-builtin def __init__(self, - intervalData: interval.Interval | str, + intervalData: interval.Interval|str, id=None, # id is okay: @ReservedAssignment direction=Direction.BI): if isinstance(intervalData, str): @@ -169,7 +169,7 @@ def __init__(self, # one or two pairs of Node ids that this Edge connects # if there are two, it is a bidirectional, w/ first ascending - self._connections: list[tuple[int | Terminus, int | Terminus]] = [] + self._connections: list[tuple[int|Terminus, int|Terminus]] = [] def __eq__(self, other): ''' @@ -192,8 +192,8 @@ def _reprInternal(self): def addDirectedConnection( self, - node1: Node | int | Terminus, - node2: Node | int | Terminus, + node1: Node|int|Terminus, + node2: Node|int|Terminus, direction=None ) -> None: ''' @@ -259,8 +259,8 @@ def addBiDirectedConnections(self, node1, node2): def getConnections( self, - direction: None | Direction = None - ) -> list[tuple[int | Terminus, int | Terminus]]: + direction: None|Direction = None + ) -> list[tuple[int|Terminus, int|Terminus]]: ''' Callable as a property (.connections) or as a method (.getConnections(direction)): @@ -311,7 +311,7 @@ def getConnections( # keep separate property, since getConnections takes a direction argument. @property - def connections(self) -> list[tuple[int | Terminus, int | Terminus]]: + def connections(self) -> list[tuple[int|Terminus, int|Terminus]]: return self.getConnections() @@ -336,10 +336,10 @@ class Node(prebase.ProtoM21Object, common.SlottedObjectMixin): # noinspection PyShadowingBuiltins # pylint: disable=redefined-builtin - def __init__(self, id: Terminus | int, degree: int, weight: float = 1.0): + def __init__(self, id: Terminus|int, degree: int, weight: float = 1.0): # store id, either as string, such as terminusLow, or a number. # ids are unique to any node in the network - self.id: Terminus | int = id + self.id: Terminus|int = id # the degree is used to define ordered node counts from the bottom # the degree is analogous to scale degree or degree # more than one node may have the same degree @@ -424,7 +424,7 @@ class IntervalNetwork: ''' def __init__(self, - edgeList: Sequence[interval.Interval | str] = (), + edgeList: Sequence[interval.Interval|str] = (), octaveDuplicating=False, deterministic=True, pitchSimplification='maxAccidental'): @@ -435,10 +435,10 @@ def __init__(self, # a dictionary of Edge object, where keys are edgeId values # Edges store directed connections between Node ids - self.edges: OrderedDict[Terminus | int, Edge] = OrderedDict() + self.edges: OrderedDict[Terminus|int, Edge] = OrderedDict() # nodes suggest Pitches, but Pitches are not stored - self.nodes: OrderedDict[Terminus | int, Node] = OrderedDict() + self.nodes: OrderedDict[Terminus|int, Node] = OrderedDict() if edgeList: # auto initialize self.fillBiDirectedEdges(edgeList) @@ -453,11 +453,11 @@ def __init__(self, # store segments self._ascendingCache: OrderedDict[ CacheKey, - tuple[list[pitch.Pitch], list[Terminus | int]] + tuple[list[pitch.Pitch], list[Terminus|int]] ] = OrderedDict() self._descendingCache: OrderedDict[ CacheKey, - tuple[list[pitch.Pitch], list[Terminus | int]] + tuple[list[pitch.Pitch], list[Terminus|int]] ] = OrderedDict() def clear(self): @@ -501,7 +501,7 @@ def __eq__(self, other): return False return True - def fillBiDirectedEdges(self, edgeList: Sequence[interval.Interval | str]): + def fillBiDirectedEdges(self, edgeList: Sequence[interval.Interval|str]): # noinspection PyShadowingNames ''' Given an ordered list of bi-directed edges given as :class:`~music21.interval.Interval` @@ -920,7 +920,7 @@ def getNodeDegreeDictionary(self, equateTermini: bool = True): If `equateTermini` is True, the terminals will be given the same degree. ''' - post: OrderedDict[Terminus | int, int] = OrderedDict() + post: OrderedDict[Terminus|int, int] = OrderedDict() for nId, n in self.nodes.items(): if equateTermini: if nId == Terminus.HIGH: @@ -1021,7 +1021,7 @@ def degreeModulus(self, degree: int) -> int: return ((degree - 1) % spanCount) + sMin def nodeNameToNodes(self, - nodeId: Node | int | Terminus | None, + nodeId: Node|int|Terminus|None, *, equateTermini=True, permitDegreeModuli=True): @@ -1214,14 +1214,14 @@ def getUnalteredPitch( def nextPitch( self, - pitchReference: pitch.Pitch | str, - nodeName: Node | int | Terminus | None, - pitchOrigin: pitch.Pitch | str, + pitchReference: pitch.Pitch|str, + nodeName: Node|int|Terminus|None, + pitchOrigin: pitch.Pitch|str, *, direction: Direction = Direction.ASCENDING, stepSize=1, alteredDegrees=None, - getNeighbor: bool | Direction = True + getNeighbor: bool|Direction = True ): # noinspection PyShadowingNames ''' @@ -1373,11 +1373,11 @@ def _getCacheKey( self, nodeObj: Node, pitchReference: pitch.Pitch, - minPitch: pitch.Pitch | None, - maxPitch: pitch.Pitch | None, + minPitch: pitch.Pitch|None, + maxPitch: pitch.Pitch|None, *, includeFirst: bool, - reverse: bool | None = None, # only meaningful for descending + reverse: bool|None = None, # only meaningful for descending ) -> CacheKey: ''' Return key for caching based on critical components. @@ -1401,14 +1401,14 @@ def _getCacheKey( def realizeAscending( self, - pitchReference: pitch.Pitch | str, - nodeId: Node | int | Terminus | None = None, - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + pitchReference: pitch.Pitch|str, + nodeId: Node|int|Terminus|None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, *, alteredDegrees=None, fillMinMaxIfNone=False - ) -> tuple[list[pitch.Pitch], list[Terminus | int]]: + ) -> tuple[list[pitch.Pitch], list[Terminus|int]]: # noinspection PyShadowingNames ''' Given a reference pitch, realize upwards to a maximum pitch. @@ -1566,10 +1566,10 @@ def realizeAscending( def realizeDescending( self, - pitchReference: pitch.Pitch | str, - nodeId: Node | int | Terminus | None = None, - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + pitchReference: pitch.Pitch|str, + nodeId: Node|int|Terminus|None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, *, alteredDegrees=None, includeFirst=False, @@ -1645,13 +1645,13 @@ def realizeDescending( else: nodeObj = self.nodeNameToNodes(nodeId)[0] - minPitchObj: pitch.Pitch | None + minPitchObj: pitch.Pitch|None if isinstance(minPitch, str): minPitchObj = pitch.Pitch(minPitch) else: minPitchObj = minPitch - maxPitchObj: pitch.Pitch | None + maxPitchObj: pitch.Pitch|None if isinstance(maxPitch, str): maxPitchObj = pitch.Pitch(maxPitch) else: @@ -1765,10 +1765,10 @@ def realizeDescending( return pre, preNodeId def realize(self, - pitchReference: str | pitch.Pitch, - nodeId: Node | int | Terminus | None = None, - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + pitchReference: str|pitch.Pitch, + nodeId: Node|int|Terminus|None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, direction: Direction = Direction.ASCENDING, alteredDegrees=None, reverse=False): @@ -1821,13 +1821,13 @@ def realize(self, if pitchRef.octave is None: pitchRef.octave = pitchRef.implicitOctave - minPitchObj: pitch.Pitch | None + minPitchObj: pitch.Pitch|None if isinstance(minPitch, str): minPitchObj = pitch.Pitch(minPitch) else: minPitchObj = minPitch - maxPitchObj: pitch.Pitch | None + maxPitchObj: pitch.Pitch|None if isinstance(maxPitch, str): maxPitchObj = pitch.Pitch(maxPitch) else: @@ -1965,10 +1965,10 @@ def realize(self, def realizePitch( self, - pitchReference: str | pitch.Pitch, - nodeId: Node | int | Terminus | None = None, - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + pitchReference: str|pitch.Pitch, + nodeId: Node|int|Terminus|None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, direction: Direction = Direction.ASCENDING, alteredDegrees=None, reverse=False, @@ -2029,9 +2029,9 @@ def realizePitch( def realizeIntervals( self, - nodeId: Node | int | Terminus | None = None, - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + nodeId: Node|int|Terminus|None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, direction: Direction = Direction.ASCENDING, alteredDegrees=None, reverse=False, @@ -2071,8 +2071,8 @@ def realizeIntervals( def realizeTermini( self, - pitchReference: str | pitch.Pitch, - nodeId: Node | int | Terminus | None = None, + pitchReference: str|pitch.Pitch, + nodeId: Node|int|Terminus|None = None, alteredDegrees=None, ) -> tuple[pitch.Pitch, pitch.Pitch]: ''' @@ -2114,8 +2114,8 @@ def realizeTermini( def realizeMinMax( self, - pitchReference: str | pitch.Pitch, - nodeId: Node | int | Terminus | None = None, + pitchReference: str|pitch.Pitch, + nodeId: Node|int|Terminus|None = None, alteredDegrees=None, ) -> tuple[pitch.Pitch, pitch.Pitch]: ''' @@ -2213,11 +2213,11 @@ def realizeMinMax( def realizePitchByDegree( self, - pitchReference: pitch.Pitch | str, - nodeId: Node | int | Terminus | None = None, + pitchReference: pitch.Pitch|str, + nodeId: Node|int|Terminus|None = None, nodeDegreeTargets=(1,), - minPitch: pitch.Pitch | str | None = None, - maxPitch: pitch.Pitch | str | None = None, + minPitch: pitch.Pitch|str|None = None, + maxPitch: pitch.Pitch|str|None = None, direction: Direction = Direction.ASCENDING, alteredDegrees=None, ): @@ -2369,9 +2369,9 @@ def plot(self, def getRelativeNodeId( self, - pitchReference: pitch.Pitch | str, - nodeId: Node | int | Terminus | None, - pitchTarget: pitch.Pitch | note.Note | str, + pitchReference: pitch.Pitch|str, + nodeId: Node|int|Terminus|None, + pitchTarget: pitch.Pitch|note.Note|str, *, comparisonAttribute: str = 'ps', direction: Direction = Direction.ASCENDING, @@ -2471,9 +2471,9 @@ def getRelativeNodeId( def getNeighborNodeIds( self, - pitchReference: pitch.Pitch | str, - nodeName: Node | int | Terminus | None, - pitchTarget: pitch.Pitch | str, + pitchReference: pitch.Pitch|str, + nodeName: Node|int|Terminus|None, + pitchTarget: pitch.Pitch|str, direction: Direction = Direction.ASCENDING, alteredDegrees=None, ): @@ -2532,9 +2532,9 @@ def getNeighborNodeIds( def getRelativeNodeDegree( self, - pitchReference: pitch.Pitch | str, + pitchReference: pitch.Pitch|str, nodeId, - pitchTarget: pitch.Pitch | str, + pitchTarget: pitch.Pitch|str, comparisonAttribute='ps', direction: Direction = Direction.ASCENDING, alteredDegrees=None, @@ -2639,8 +2639,8 @@ def getRelativeNodeDegree( def getPitchFromNodeDegree( self, - pitchReference: pitch.Pitch | str, - nodeName: Node | int | Terminus | None, + pitchReference: pitch.Pitch|str, + nodeName: Node|int|Terminus|None, nodeDegreeTarget, direction: Direction = Direction.ASCENDING, minPitch=None, @@ -2820,7 +2820,7 @@ def filterPitchList( return pitchList, minPitch, maxPitch def match(self, - pitchReference: pitch.Pitch | str, + pitchReference: pitch.Pitch|str, nodeId, pitchTarget, comparisonAttribute='pitchClass', @@ -2896,7 +2896,7 @@ def match(self, return matched, noMatch def findMissing(self, - pitchReference: pitch.Pitch | str, + pitchReference: pitch.Pitch|str, nodeId, pitchTarget, comparisonAttribute='pitchClass', diff --git a/music21/scale/scala/__init__.py b/music21/scale/scala/__init__.py index d74467a279..0d416d1659 100644 --- a/music21/scale/scala/__init__.py +++ b/music21/scale/scala/__init__.py @@ -62,7 +62,7 @@ # ------------------------------------------------------------------------------ # global variable to cache the paths returned from getPaths() -SCALA_PATHS: dict[str, dict[str, list[str]] | None] = {'allPaths': None} +SCALA_PATHS: dict[str, dict[str, list[str]]|None] = {'allPaths': None} def getPaths(): ''' diff --git a/music21/search/base.py b/music21/search/base.py index b420e9b2b4..b46e83d23a 100644 --- a/music21/search/base.py +++ b/music21/search/base.py @@ -196,7 +196,7 @@ class StreamSearcher: ''' def __init__(self, streamSearch: Stream, searchList: list[m21Base.Music21Object]): - self.streamSearch: Stream | iterator.StreamIterator = streamSearch + self.streamSearch: Stream|iterator.StreamIterator = streamSearch self.searchList: list[m21Base.Music21Object] = searchList self.recurse: bool = False self.filterNotes: bool = False @@ -204,10 +204,10 @@ def __init__(self, streamSearch: Stream, searchList: list[m21Base.Music21Object] self.algorithms: list[ Callable[[StreamSearcher, m21Base.Music21Object, m21Base.Music21Object], - bool | None] + bool|None] ] = [StreamSearcher.wildcardAlgorithm] - self.activeIterator: iterator.StreamIterator | None = None + self.activeIterator: iterator.StreamIterator|None = None def run(self) -> list[SearchMatch]: thisStreamIterator: iterator.StreamIterator diff --git a/music21/search/lyrics.py b/music21/search/lyrics.py index e1e929fccd..f6e3cfa9d3 100644 --- a/music21/search/lyrics.py +++ b/music21/search/lyrics.py @@ -135,12 +135,12 @@ class LyricSearcher: found if a work contains multiple voices. ''' - def __init__(self, s: StreamType | None = None): - self.stream: StreamType | None = s + def __init__(self, s: StreamType|None = None): + self.stream: StreamType|None = s self.includeIntermediateElements = False # currently does nothing self.includeTrailingMelisma = False # currently does nothing - self._indexText: str | None = None + self._indexText: str|None = None self._indexTuples: list[IndexedLyric] = [] @property @@ -200,10 +200,10 @@ def index(self, s=None) -> list[IndexedLyric]: else: self.stream = s - indexByIdentifier: OrderedDict[str | int, list[IndexedLyric]] = OrderedDict() - iTextByIdentifier: OrderedDict[str | int, str] = OrderedDict() - lastSyllabicByIdentifier: OrderedDict[str | int, - str | None] = OrderedDict() + indexByIdentifier: OrderedDict[str|int, list[IndexedLyric]] = OrderedDict() + iTextByIdentifier: OrderedDict[str|int, str] = OrderedDict() + lastSyllabicByIdentifier: OrderedDict[str|int, + str|None] = OrderedDict() for n in s.recurse().notes: ls: list[note.Lyric] = n.lyrics diff --git a/music21/serial.py b/music21/serial.py index 536f3dfaa3..741c718652 100644 --- a/music21/serial.py +++ b/music21/serial.py @@ -1084,14 +1084,14 @@ class HistoricalTwelveToneRow(TwelveToneRow): 'title': 'The title of the work, or None. (String)', } - composer: None | str = None - opus: None | str = None - title: None | str = None + composer: None|str = None + opus: None|str = None + title: None|str = None def __init__(self, - composer: None | str = None, - opus: None | str = None, - title: None | str = None, + composer: None|str = None, + opus: None|str = None, + title: None|str = None, row=None, **keywords): super().__init__(row, **keywords) diff --git a/music21/sieve.py b/music21/sieve.py index a392f38b93..d5f83f561b 100644 --- a/music21/sieve.py +++ b/music21/sieve.py @@ -1010,7 +1010,7 @@ class Sieve: >>> c = sieve.Sieve('(5|2)&4&8') ''' - def __init__(self, usrStr: str | list[str], z: list[int] | None = None): + def __init__(self, usrStr: str|list[str], z: list[int]|None = None): # note: this z should only be used if usrStr is a str, and not a list if z is None and isinstance(usrStr, str): z = list(range(100)) @@ -1629,7 +1629,7 @@ def _cmpSegment(self): def segment( self, - state: t.Literal['cmp'] | t.Literal['exp'] | None = None, + state: t.Literal['cmp']|t.Literal['exp']|None = None, n=0, z=None, segmentFormat=None @@ -1841,10 +1841,10 @@ class PitchSieve: def __init__(self, sieveString, - pitchLower: str | None = None, - pitchUpper: str | None = None, - pitchOrigin: str | None = None, - eld: int | float = 1): + pitchLower: str|None = None, + pitchUpper: str|None = None, + pitchOrigin: str|None = None, + eld: int|float = 1): self.sieveString = sieveString # logical sieve string # should be in a try block @@ -1977,7 +1977,7 @@ def getIntervalSequence(self) -> list[interval.Interval]: # self.sieveObject.period()) p = self.sieveObject.period() - z: list[int] | None + z: list[int]|None if p < 999999999: z = list(range(p + 1)) else: # too big to get z as list of values diff --git a/music21/sites.py b/music21/sites.py index d9df1c27f5..3d2ca21641 100644 --- a/music21/sites.py +++ b/music21/sites.py @@ -43,7 +43,7 @@ # that still exists, then restore it from the dictionary; otherwise, do not # sweat it. Should make pickle deepcopies of music21 objects in Streams still # possible without needing to recreate the whole stream. -GLOBAL_SITE_STATE_DICT: MutableMapping[str, t.Any | None] = weakref.WeakValueDictionary() +GLOBAL_SITE_STATE_DICT: MutableMapping[str, t.Any|None] = weakref.WeakValueDictionary() class SitesException(exceptions21.Music21Exception): @@ -404,7 +404,7 @@ def yieldSites(self, excludeNone: bool = False, sortByCreationTime: t.Union[bool, t.Literal['reverse']] = False, priorityTarget=None, - ) -> Generator[stream.Stream | None, None, None]: + ) -> Generator[stream.Stream|None, None, None]: yield None def yieldSites(self, @@ -412,7 +412,7 @@ def yieldSites(self, excludeNone: bool = False, sortByCreationTime: t.Union[bool, t.Literal['reverse']] = False, priorityTarget=None, - ) -> Generator[stream.Stream | None, None, None]: + ) -> Generator[stream.Stream|None, None, None]: # noinspection PyDunderSlots ''' Yield references; order, based on dictionary keys, is from least diff --git a/music21/spanner.py b/music21/spanner.py index 3d5725e436..140466f3f8 100644 --- a/music21/spanner.py +++ b/music21/spanner.py @@ -239,7 +239,7 @@ def __init__(self, # parameters that spanners need in loading and processing # local id is the id for the local area; used by musicxml - self.idLocal: str | None = None + self.idLocal: str|None = None # after all spannedElements have been gathered, setting complete # will mark that all parts have been gathered. self.completeStatus: bool = False @@ -258,7 +258,7 @@ def __init__(self, # (False means fill is needed, True means fill is not # needed, presumably because the fill was done by hand). # Initialized to 'unknown'. - self.filledStatus: bool | t.Literal['unknown'] = 'unknown' + self.filledStatus: bool|t.Literal['unknown'] = 'unknown' def _reprInternal(self): msg = [] @@ -548,7 +548,7 @@ def replaceSpannedElement(self, old, new) -> None: def fill( self, - searchStream=None, # stream.Stream | None, but cannot import stream here + searchStream=None, # stream.Stream|None, but cannot import stream here *, includeEndBoundary: bool = False, mustFinishInSpan: bool = False, @@ -595,7 +595,7 @@ def fill( # Don't fill twice. If client wants a refill they can set filledStatus to False. return - startElement: base.Music21Object | None = self.getFirst() + startElement: base.Music21Object|None = self.getFirst() if startElement is None: # no spanned elements? Nothing to fill. return @@ -611,7 +611,7 @@ def fill( from music21 import stream assert isinstance(searchStream, stream.Stream) - endElement: base.Music21Object | None = self.getLast() + endElement: base.Music21Object|None = self.getLast() if endElement is startElement: endElement = None @@ -830,7 +830,7 @@ class SpannerBundle(prebase.ProtoM21Object): Creators of SpannerBundles are required to check that this constraint is True ''' # TODO: make SpannerBundle a Generic type - def __init__(self, spanners: list[Spanner] | None = None): + def __init__(self, spanners: list[Spanner]|None = None): self._cache: dict[str, t.Any] = {} # cache is defined on Music21Object not ProtoM21Object self._storage: list[Spanner] = [] @@ -899,7 +899,7 @@ def getSpannerStorageIds(self) -> list[int]: post.append(id(x.spannerStorage)) return post - def getByIdLocal(self, idLocal: int | None = None) -> SpannerBundle: + def getByIdLocal(self, idLocal: int|None = None) -> SpannerBundle: ''' Get spanners by `idLocal`. @@ -1072,7 +1072,7 @@ def replaceSpannedElement( return replacedSpanners - def getByClass(self, searchClass: str | type | tuple[type, ...]) -> 'SpannerBundle': + def getByClass(self, searchClass: str|type|tuple[type, ...]) -> 'SpannerBundle': ''' Given a spanner class, return a new SpannerBundle of all Spanners of the desired class. @@ -1519,8 +1519,8 @@ class RepeatBracket(Spanner): def __init__(self, *spannedElements, - number: int | str | Iterable[int] = 0, - overrideDisplay: str | None = None, + number: int|str|Iterable[int] = 0, + overrideDisplay: str|None = None, **keywords): super().__init__(*spannedElements, **keywords) @@ -1564,7 +1564,7 @@ def _getNumber(self) -> str: else: # range of values return f'{self.numberRange[0]}-{self.numberRange[-1]}' - def _setNumber(self, value: int | str | Iterable[int]): + def _setNumber(self, value: int|str|Iterable[int]): ''' Set the bracket number. There may be range of values provided ''' @@ -1901,8 +1901,8 @@ def __init__( tick: str = 'down', startTick: str = 'down', endTick: str = 'down', - startHeight: int | float | None = None, - endHeight: int | float | None = None, + startHeight: int|float|None = None, + endHeight: int|float|None = None, **keywords ): super().__init__(*spannedElements, **keywords) @@ -2064,7 +2064,7 @@ class Glissando(Spanner): def __init__(self, *spannedElements, lineType: str = 'wavy', - label: str | None = None, + label: str|None = None, **keywords): super().__init__(*spannedElements, **keywords) # from music21 import note diff --git a/music21/stream/base.py b/music21/stream/base.py index cb668c3aaf..8e03fbe211 100644 --- a/music21/stream/base.py +++ b/music21/stream/base.py @@ -82,7 +82,7 @@ ImmutableStreamException = exceptions21.ImmutableStreamException T = t.TypeVar('T') -RecursiveLyricList = note.Lyric | None | list['RecursiveLyricList'] +RecursiveLyricList = note.Lyric|None|list['RecursiveLyricList'] BestQuantizationMatch = namedtuple( 'BestQuantizationMatch', @@ -261,7 +261,7 @@ def __init__(self, givenElements, craziness, **keywords): # forms of checking class isStream = True isMeasure = False - classSortOrder: int | float = -20 + classSortOrder: int|float = -20 recursionType: RecursionType = RecursionType.ELEMENTS_FIRST _styleClass = style.StreamStyle @@ -340,7 +340,7 @@ def __init__(self, self.definesExplicitPageBreaks = False # property for transposition status; - self._atSoundingPitch: bool | t.Literal['unknown'] = 'unknown' + self._atSoundingPitch: bool|t.Literal['unknown'] = 'unknown' # experimental self._mutable = True @@ -732,7 +732,7 @@ def __getitem__(self, f'got {type(k)}' ) - def first(self) -> M21ObjType | None: + def first(self) -> M21ObjType|None: ''' Return the first element of a Stream. (Added for compatibility with StreamIterator) Or None if the Stream is empty. @@ -758,7 +758,7 @@ def first(self) -> M21ObjType | None: except IndexError: return None - def last(self) -> M21ObjType | None: + def last(self) -> M21ObjType|None: ''' Return the last element of a Stream. (Added for compatibility with StreamIterator) Or None if the Stream is empty. @@ -918,7 +918,7 @@ def elements(self) -> tuple[M21ObjType, ...]: return tuple(self._cache['elements']) @elements.setter - def elements(self, value: Stream | Iterable[base.Music21Object]): + def elements(self, value: Stream|Iterable[base.Music21Object]): ''' Sets this stream's elements to the elements in another stream (just give the stream, not the stream's .elements), or to a list of elements. @@ -1120,7 +1120,7 @@ def __bool__(self): # ------------------------------ @property - def clef(self) -> clef.Clef | None: + def clef(self) -> clef.Clef|None: ''' Finds or sets a :class:`~music21.clef.Clef` at offset 0.0 in the Stream (generally a Measure): @@ -1161,7 +1161,7 @@ def clef(self) -> clef.Clef | None: return clefList.first() @clef.setter - def clef(self, clefObj: clef.Clef | None): + def clef(self, clefObj: clef.Clef|None): # if clef is None; remove object? oldClef = self.clef if oldClef is not None: @@ -1174,7 +1174,7 @@ def clef(self, clefObj: clef.Clef | None): self.insert(0.0, clefObj) @property - def timeSignature(self) -> meter.TimeSignature | None: + def timeSignature(self) -> meter.TimeSignature|None: ''' Gets or sets the timeSignature at offset 0.0 of the Stream (generally a Measure) @@ -1226,7 +1226,7 @@ def timeSignature(self) -> meter.TimeSignature | None: return tsList.first() @timeSignature.setter - def timeSignature(self, tsObj: meter.TimeSignature | None): + def timeSignature(self, tsObj: meter.TimeSignature|None): oldTimeSignature = self.timeSignature if oldTimeSignature is not None: # environLocal.printDebug(['removing ts', oldTimeSignature]) @@ -1238,7 +1238,7 @@ def timeSignature(self, tsObj: meter.TimeSignature | None): self.insert(0, tsObj) @property - def keySignature(self) -> key.KeySignature | None: + def keySignature(self) -> key.KeySignature|None: ''' Find or set a Key or KeySignature at offset 0.0 of a stream. @@ -1275,7 +1275,7 @@ def keySignature(self) -> key.KeySignature | None: return None @keySignature.setter - def keySignature(self, keyObj: key.KeySignature | None): + def keySignature(self, keyObj: key.KeySignature|None): ''' >>> a = stream.Measure() >>> a.keySignature = key.KeySignature(6) @@ -1382,7 +1382,7 @@ def clear(self) -> None: ''' self.elements = () - def cloneEmpty(self: StreamType, derivationMethod: str | None = None) -> StreamType: + def cloneEmpty(self: StreamType, derivationMethod: str|None = None) -> StreamType: ''' Create a Stream that is identical to this one except that the elements are empty and set derivation. @@ -1626,7 +1626,7 @@ def index(self, el: base.Music21Object) -> int: raise StreamException(f'cannot find object ({el}) in Stream') def remove(self, - targetOrList: base.Music21Object | Sequence[base.Music21Object], + targetOrList: base.Music21Object|Sequence[base.Music21Object], *, shiftOffsets=False, recurse=False): @@ -1852,7 +1852,7 @@ def remove(self, # pass # This should maybe just call a function renumberMeasures self.coreElementsChanged(clearIsSorted=False) - def pop(self, index: int | None = None) -> base.Music21Object: + def pop(self, index: int|None = None) -> base.Music21Object: ''' Return and remove the object found at the user-specified index value. Index values are @@ -1980,7 +1980,7 @@ class or subclass in the Stream in place. # pylint: disable=no-member def _deepcopySubclassable(self: StreamType, - memo: dict[int, t.Any] | None = None, + memo: dict[int, t.Any]|None = None, *, ignoreAttributes=None, ) -> StreamType: @@ -2093,7 +2093,7 @@ def _replaceSpannerBundleForDeepcopy(self, new): def setElementOffset( self, element: base.Music21Object, - offset: int | float | Fraction | OffsetSpecial, + offset: int|float|Fraction|OffsetSpecial, ): ''' Sets the Offset for an element that is already in a given stream. @@ -3409,10 +3409,10 @@ def _reprTextLine(self, *, addEndTimes=False, useMixedNumerals=False) -> str: # display methods; in the same manner as show() and write() def plot(self, - plotFormat: str | None = None, - xValue: str | None = None, - yValue: str | None = None, - zValue: str | None = None, + plotFormat: str|None = None, + xValue: str|None = None, + yValue: str|None = None, + zValue: str|None = None, *, returnInNotebook: bool = False, **keywords): @@ -3591,7 +3591,7 @@ def addGroupForElements(self, @overload def getElementsByClass(self, - classFilterList: str | Iterable[str] + classFilterList: str|Iterable[str] ) -> iterator.StreamIterator[M21ObjType]: # Remove all dummy code once Astroid #1015 is fixed x: iterator.StreamIterator[M21ObjType] = self.iter() @@ -3759,7 +3759,7 @@ def getElementsByGroup(self, groupFilterList) -> iterator.StreamIterator: ''' return self.iter().getElementsByGroup(groupFilterList, returnClone=False) - def getElementById(self, elementId) -> base.Music21Object | None: + def getElementById(self, elementId) -> base.Music21Object|None: ''' Returns the first encountered element for a given id. Return None if no match. Note: this uses the id attribute stored on elements, @@ -4058,7 +4058,7 @@ def getElementAtOrBefore( ] = None, *, _beforeNotAt: bool = False, - ) -> base.Music21Object | None: + ) -> base.Music21Object|None: # noinspection PyShadowingNames ''' Given an offset, find the element at this offset, @@ -4190,7 +4190,7 @@ def getElementBeforeOffset( Iterable[type], None, ] = None, - ) -> base.Music21Object | None: + ) -> base.Music21Object|None: ''' Get element before (and not at) a provided offset. @@ -4339,8 +4339,8 @@ def getElementAfterElement(self, element, classList=None): # _getNotes and _getPitches are found with the interval routines def _getMeasureNumberListByStartEnd( self, - numberStart: int | str, - numberEnd: int | str, + numberStart: int|str, + numberEnd: int|str, *, indicesNotNumbers: bool ) -> list[Measure]: @@ -4609,7 +4609,7 @@ def measures( This is in OMIT ''' - startMeasure: Measure | None + startMeasure: Measure|None returnObj = t.cast(Stream[Measure], self.cloneEmpty(derivationMethod='measures')) srcObj = self @@ -4665,7 +4665,7 @@ def measure(self, measureNumber, *, collect=('Clef', 'TimeSignature', 'Instrument', 'KeySignature'), - indicesNotNumbers=False) -> Measure | None: + indicesNotNumbers=False) -> Measure|None: ''' Given a measure number, return a single :class:`~music21.stream.Measure` object if the Measure number exists, otherwise return None. @@ -4950,8 +4950,8 @@ def optionalAddRest(): def measureOffsetMap( self, - classFilterList: list[t.Type] | list[str] | tuple[t.Type] | tuple[str] = ('Measure',) - ) -> OrderedDict[float | Fraction, list[Measure]]: + classFilterList: list[t.Type]|list[str]|tuple[t.Type]|tuple[str] = ('Measure',) + ) -> OrderedDict[float|Fraction, list[Measure]]: ''' If this Stream contains Measures, returns an OrderedDict whose keys are the offsets of the start of each measure @@ -5037,7 +5037,7 @@ def measureOffsetMap( # environLocal.printDebug(['calling measure offsetMap()']) # environLocal.printDebug([classFilterList]) - offsetMap: dict[float | Fraction, list[Measure]] = {} + offsetMap: dict[float|Fraction, list[Measure]] = {} # first, try to get measures # this works best of this is a Part or Score if Measure in classFilterList or 'Measure' in classFilterList: @@ -5206,7 +5206,7 @@ def spanners(self) -> iterator.StreamIterator[spanner.Spanner]: # handling transposition values and status @property - def atSoundingPitch(self) -> bool | t.Literal['unknown']: + def atSoundingPitch(self) -> bool|t.Literal['unknown']: ''' Get or set the atSoundingPitch status, that is whether the score is at concert pitch or may have transposing instruments @@ -5230,7 +5230,7 @@ def atSoundingPitch(self) -> bool | t.Literal['unknown']: return self._atSoundingPitch @atSoundingPitch.setter - def atSoundingPitch(self, value: bool | t.Literal['unknown']): + def atSoundingPitch(self, value: bool|t.Literal['unknown']): if value in [True, False, 'unknown']: self._atSoundingPitch = value else: @@ -5265,7 +5265,7 @@ def _transposeByInstrument( transposeKeySignature: bool = True, preserveAccidentalDisplay: bool = False, inPlace: bool = False, - ) -> StreamType | None: + ) -> StreamType|None: ''' Transpose the Stream according to each instrument's transposition. @@ -5329,7 +5329,7 @@ def _transposeByInstrument( return returnObj - def _treatAtSoundingPitch(self) -> bool | str: + def _treatAtSoundingPitch(self) -> bool|str: ''' `atSoundingPitch` might be True, False, or 'unknown'. Given that setting the property does not automatically synchronize the corresponding @@ -5736,7 +5736,7 @@ def getInstruments(self, * Changed in v8: recurse is True by default. ''' - instObj: instrument.Instrument | None = None + instObj: instrument.Instrument|None = None if not recurse: sIter = self.iter() @@ -5780,7 +5780,7 @@ def getInstrument(self, *, searchActiveSite=True, returnDefault=True, - recurse=False) -> instrument.Instrument | None: + recurse=False) -> instrument.Instrument|None: ''' Return the first Instrument found in this Stream, or None. @@ -6704,18 +6704,18 @@ def makeBeams(self, *, inPlace=False, setStemDirections=True, failOnNoTimeSignat def makeAccidentals( self, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - useKeySignature: bool | key.KeySignature = True, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + useKeySignature: bool|key.KeySignature = True, + alteredPitches: list[pitch.Pitch]|None = None, searchKeySignatureByContext: bool = False, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, inPlace: bool = False, overrideStatus: bool = False, cautionaryNotImmediateRepeat: bool = True, - tiePitchSet: set[str] | None = None + tiePitchSet: set[str]|None = None ): ''' A method to set and provide accidentals given various conditions and contexts. @@ -6819,7 +6819,7 @@ def makeAccidentals( if tiePitchSet is None: tiePitchSet = set() - last_measure: Measure | None = None + last_measure: Measure|None = None for e in noteIterator: if e.activeSite is not None and e.activeSite.isMeasure: @@ -6943,15 +6943,15 @@ def makeNotation(self: StreamType, refStreamOrTimeRange=None, inPlace=False, bestClef=False, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - useKeySignature: bool | key.KeySignature = True, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + useKeySignature: bool|key.KeySignature = True, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, cautionaryNotImmediateRepeat: bool = True, - tiePitchSet: set[str] | None = None + tiePitchSet: set[str]|None = None ): ''' This method calls a sequence of Stream methods on this Stream to prepare @@ -6988,7 +6988,7 @@ def makeNotation(self: StreamType, * Changed in v7: `inPlace=True` returns `None`. ''' # determine what is the object to work on first - returnStream: StreamType | Stream[t.Any] + returnStream: StreamType|Stream[t.Any] if inPlace: returnStream = self else: @@ -7150,7 +7150,7 @@ def stripTies( *, inPlace: bool = False, matchByPitch: bool = True, - ) -> StreamType | None: + ) -> StreamType|None: # noinspection PyShadowingNames ''' Find all notes that are tied; remove all tied notes, @@ -8224,7 +8224,7 @@ def containerInHierarchy( el: base.Music21Object, *, setActiveSite=True - ) -> Stream | None: + ) -> Stream|None: ''' Returns the container in a hierarchy that this element belongs to. @@ -8852,7 +8852,7 @@ def _getSecondsMap(self, srcObj=None): # -------------------------------------------------------------------------- # Metadata access - def _getMetadata(self) -> metadata.Metadata | None: + def _getMetadata(self) -> metadata.Metadata|None: ''' >>> a = stream.Stream() >>> a.metadata = metadata.Metadata() @@ -8862,7 +8862,7 @@ def _getMetadata(self) -> metadata.Metadata | None: mdList = mdList.getElementsByOffset(0) return mdList.first() - def _setMetadata(self, metadataObj: metadata.Metadata | None) -> None: + def _setMetadata(self, metadataObj: metadata.Metadata|None) -> None: ''' >>> a = stream.Stream() >>> a.metadata = metadata.Metadata() @@ -9043,7 +9043,7 @@ def beatAndMeasureFromOffset(self, searchOffset, fixZeros=True): def transpose( self, - value: str | int | 'music21.interval.IntervalBase', + value: str|int|'music21.interval.IntervalBase', /, *, inPlace=False, @@ -9097,7 +9097,7 @@ def transpose( else: post = self - intv: interval.Interval | interval.GenericInterval + intv: interval.Interval|interval.GenericInterval if isinstance(value, (int, str)): intv = interval.Interval(value) elif isinstance(value, interval.ChromaticInterval): @@ -9472,7 +9472,7 @@ def findNextElementNotCoincident( useStream: Stream, startIndex: int, startOffset: OffsetQL, - ) -> tuple[base.Music21Object | None, BestQuantizationMatch | None]: + ) -> tuple[base.Music21Object|None, BestQuantizationMatch|None]: for next_el in useStream._elements[startIndex:]: next_offset = useStream.elementOffset(next_el) look_ahead_result = bestMatch(float(next_offset), quarterLengthDivisors) @@ -10266,7 +10266,7 @@ def findConsecutiveNotes( getOverlaps: bool = False, noNone: t.Literal[False] = False, **keywords - ) -> list[note.NotRest | None]: + ) -> list[note.NotRest|None]: return [] def findConsecutiveNotes( @@ -10281,7 +10281,7 @@ def findConsecutiveNotes( noNone: bool = False, **keywords ) -> t.Union[ - list[note.NotRest | None], + list[note.NotRest|None], list[note.NotRest], list[note.Note], ]: @@ -10344,7 +10344,7 @@ def findConsecutiveNotes( ''' if self.isSorted is False and self.autoSort: self.sort() - returnList: list[note.NotRest | None] = [] + returnList: list[note.NotRest|None] = [] lastStart: OffsetQL = 0.0 lastEnd: OffsetQL = 0.0 lastContainerEnd: OffsetQL = 0.0 @@ -11239,7 +11239,7 @@ def makeVoices(self, *, inPlace=False, fillGaps=True): if not inPlace: return returnObj - def _maxVoiceCount(self, *, countById=False) -> int | tuple[int, list[str]]: + def _maxVoiceCount(self, *, countById=False) -> int|tuple[int, list[str]]: ''' Returns the maximum number of voices in a part. Used by voicesToParts. Minimum returned is 1. If `countById` is True, returns a tuple of @@ -13008,7 +13008,7 @@ class Measure(Stream): for the amount of padding on the right side of a region.)''', } - def __init__(self, *args, number: int | str = 0, **keywords): + def __init__(self, *args, number: int|str = 0, **keywords): if len(args) == 1 and isinstance(args[0], int) and number == 0: number = args[0] args = () @@ -14038,8 +14038,8 @@ def expandRepeats(self: Score, copySpanners: bool = True) -> Score: def measureOffsetMap( self, - classFilterList: list[t.Type] | list[str] | tuple[t.Type] | tuple[str] = ('Measure',) - ) -> OrderedDict[float | Fraction, list[Measure]]: + classFilterList: list[t.Type]|list[str]|tuple[t.Type]|tuple[str] = ('Measure',) + ) -> OrderedDict[float|Fraction, list[Measure]]: ''' This Score method overrides the :meth:`~music21.stream.Stream.measureOffsetMap` method of Stream. @@ -14057,7 +14057,7 @@ def measureOffsetMap( if not parts: return Stream.measureOffsetMap(self, classFilterList) # else: - offsetMap: dict[float | Fraction, list[Measure]] = {} + offsetMap: dict[float|Fraction, list[Measure]] = {} for p in parts: mapPartial = p.measureOffsetMap(classFilterList) # environLocal.printDebug(['mapPartial', mapPartial]) @@ -14094,7 +14094,7 @@ def sliceByGreatestDivisor( *, addTies: bool = True, inPlace: bool = False, - ) -> Score | None: + ) -> Score|None: ''' Slice all duration of all part by the minimum duration that can be summed to each concurrent duration. @@ -14117,7 +14117,7 @@ def sliceByGreatestDivisor( if mCount == 0: mCount = 1 # treat as a single measure - m_or_p: Measure | Part + m_or_p: Measure|Part for i in range(mCount): # may be 1 uniqueQuarterLengths = [] p: Part @@ -14155,7 +14155,7 @@ def sliceByGreatestDivisor( return returnObj def partsToVoices(self, - voiceAllocation: int | list[list | int] = 2, + voiceAllocation: int|list[list|int] = 2, permitOneVoicePerPart=False, setStems=True): # noinspection PyShadowingNames @@ -14200,7 +14200,7 @@ def partsToVoices(self, bundle.append(sub) # else, assume it is a list of groupings elif common.isIterable(voiceAllocation): - voiceAllocation = t.cast(list[list | int], voiceAllocation) + voiceAllocation = t.cast(list[list|int], voiceAllocation) for group in voiceAllocation: sub = [] # if a single entry @@ -14219,7 +14219,7 @@ def partsToVoices(self, s = self.cloneEmpty(derivationMethod='partsToVoices') s.metadata = self.metadata - pActive: Part | None + pActive: Part|None for sub in bundle: # each sub contains parts if len(sub) == 1 and not permitOneVoicePerPart: # probably need to create a new part and measure @@ -14564,7 +14564,7 @@ class SpannerStorage(Stream): * Changed in v8: spannerParent is renamed client. ''' - def __init__(self, givenElements=None, *, client: spanner.Spanner | None = None, **keywords): + def __init__(self, givenElements=None, *, client: spanner.Spanner|None = None, **keywords): # No longer need store as weakref since Py2.3 and better references if client is None: # should never be none. Just for testing from music21 import spanner diff --git a/music21/stream/core.py b/music21/stream/core.py index a97efeae9f..9bc3d059f8 100644 --- a/music21/stream/core.py +++ b/music21/stream/core.py @@ -168,7 +168,7 @@ def coreAppend( def coreSetElementOffset( self, element: Music21Object, - offset: int | float | Fraction | OffsetSpecial, + offset: int|float|Fraction|OffsetSpecial, *, addElement=False, setActiveSite=True @@ -212,7 +212,7 @@ def coreElementsChanged( *, updateIsFlat: bool = True, clearIsSorted: bool = True, - memo: list[int] | None = None, + memo: list[int]|None = None, keepIndex: bool = False, ) -> None: ''' @@ -546,8 +546,8 @@ def coreGatherMissingSpanners( recurse: bool = True, requireAllPresent: bool = True, insert: bool = True, - constrainingSpannerBundle: spanner.SpannerBundle | None = None - ) -> list[spanner.Spanner] | None: + constrainingSpannerBundle: spanner.SpannerBundle|None = None + ) -> list[spanner.Spanner]|None: ''' find all spanners that are referenced by elements in the (recursed if recurse=True) stream and either inserts them in the Stream @@ -692,7 +692,7 @@ def coreGatherMissingSpanners( {1.0} ''' sb = self.spannerBundle - sIter: StreamIterator | RecursiveIterator + sIter: StreamIterator|RecursiveIterator if recurse is True: sIter = self.recurse() # type: ignore else: diff --git a/music21/stream/filters.py b/music21/stream/filters.py index 3ef82da162..105855818e 100644 --- a/music21/stream/filters.py +++ b/music21/stream/filters.py @@ -74,7 +74,7 @@ class StreamFilter(prebase.ProtoM21Object): def reset(self): pass - def __call__(self, item, iterator: StreamIteratorType | None = None): + def __call__(self, item, iterator: StreamIteratorType|None = None): return True class IsFilter(StreamFilter): diff --git a/music21/stream/iterator.py b/music21/stream/iterator.py index c4a1528c62..5c9bf2c40c 100644 --- a/music21/stream/iterator.py +++ b/music21/stream/iterator.py @@ -51,11 +51,11 @@ class StreamIteratorInefficientWarning(UserWarning): class ActiveInformation(t.TypedDict, total=False): - stream: stream.Stream | None + stream: stream.Stream|None elementIndex: int iterSection: t.Literal['_elements', '_endElements'] sectionIndex: int - lastYielded: base.Music21Object | None + lastYielded: base.Music21Object|None @@ -131,9 +131,9 @@ def __init__(self, srcStream: StreamType, *, # restrictClass: type[M21ObjType] = base.Music21Object, - filterList: list[FilterType] | None = None, + filterList: list[FilterType]|None = None, restoreActiveSites: bool = True, - activeInformation: ActiveInformation | None = None, + activeInformation: ActiveInformation|None = None, ignoreSorting: bool = False): if not ignoreSorting and srcStream.isSorted is False and srcStream.autoSort: srcStream.sort() @@ -154,7 +154,7 @@ def __init__(self, self.cleanupOnStop: bool = False self.restoreActiveSites: bool = restoreActiveSites - self.overrideDerivation: str | None = None + self.overrideDerivation: str|None = None if filterList is None: filterList = [] @@ -166,8 +166,8 @@ def __init__(self, # return True or False for an element for # whether it should be yielded. self.filters: list[FilterType] = filterList - self._len: int | None = None - self._matchingElements: dict[bool | None, list[M21ObjType]] = {} + self._len: int|None = None + self._matchingElements: dict[bool|None, list[M21ObjType]] = {} # keep track of where we are in the parse. # esp important for recursive streams... if activeInformation is not None: @@ -331,10 +331,10 @@ def __getitem__(self, k: slice) -> list[M21ObjType]: return self.matchingElements() @overload - def __getitem__(self, k: str) -> M21ObjType | None: + def __getitem__(self, k: str) -> M21ObjType|None: return None - def __getitem__(self, k: int | slice | str) -> M21ObjType | list[M21ObjType] | None: + def __getitem__(self, k: int|slice|str) -> M21ObjType|list[M21ObjType]|None: ''' Iterators can request other items by index or slice. @@ -524,7 +524,7 @@ def clone(self: StreamIteratorType) -> StreamIteratorType: ) return out - def first(self) -> M21ObjType | None: + def first(self) -> M21ObjType|None: ''' Efficiently return the first matching element, or None if no elements match. @@ -574,7 +574,7 @@ def first(self) -> M21ObjType | None: except StopIteration: return None - def last(self) -> M21ObjType | None: + def last(self) -> M21ObjType|None: ''' Returns the last matching element, or None if no elements match. @@ -659,7 +659,7 @@ def cleanup(self) -> None: # cleanupOnStop is rarely used, so we put in # a dummy stream so that srcStream does not need - # to be x | None + # to be x|None SrcStreamClass = self.srcStream.__class__ del self.srcStream @@ -673,7 +673,7 @@ def cleanup(self) -> None: def matchingElements( self, *, - restoreActiveSites: bool | None = None + restoreActiveSites: bool|None = None ) -> list[M21ObjType]: ''' Returns a list of elements that match the filter. @@ -811,7 +811,7 @@ def stream(self, returnStreamSubClass: t.Literal[True] = True) -> StreamType: # x: StreamType = self.streamObj return x - def stream(self, returnStreamSubClass=True) -> stream.Stream | StreamType: + def stream(self, returnStreamSubClass=True) -> stream.Stream|StreamType: ''' return a new stream from this iterator. @@ -880,7 +880,7 @@ def stream(self, returnStreamSubClass=True) -> stream.Stream | StreamType: # if this stream was sorted, the resultant stream is sorted clearIsSorted = False - found: stream.Stream | StreamType + found: stream.Stream|StreamType if returnStreamSubClass is True: try: found = ss.__class__() @@ -985,7 +985,7 @@ def removeFilter( return out - def getElementById(self, elementId: str) -> M21ObjType | None: + def getElementById(self, elementId: str) -> M21ObjType|None: ''' Returns a single element (or None) that matches elementId. @@ -1810,7 +1810,7 @@ def __init__( if streamsOnly is True: self.filters.append(filters.ClassFilter('Stream')) - self.childRecursiveIterator: RecursiveIterator[t.Any] | None = None + self.childRecursiveIterator: RecursiveIterator[t.Any]|None = None # not yet used. # self.parentIterator = None diff --git a/music21/stream/makeNotation.py b/music21/stream/makeNotation.py index 1e4c4f631e..f7f60b3dff 100644 --- a/music21/stream/makeNotation.py +++ b/music21/stream/makeNotation.py @@ -55,7 +55,7 @@ def makeBeams( inPlace=False, setStemDirections=True, failOnNoTimeSignature=False, -) -> StreamType | None: +) -> StreamType|None: # noinspection PyShadowingNames ''' Return a new Measure, or Stream of Measures, with beams applied to all @@ -202,7 +202,7 @@ def makeBeams( continue # getBeams - offset: float | Fraction = 0.0 + offset: float|Fraction = 0.0 if m.paddingLeft != 0.0: offset = opFrac(m.paddingLeft) elif m.paddingRight != 0.0: @@ -239,7 +239,7 @@ def makeMeasures( finalBarline='final', bestClef=False, inPlace=False, -) -> StreamType | None: +) -> StreamType|None: ''' Takes a stream and places all of its elements into measures (:class:`~music21.stream.Measure` objects) @@ -718,7 +718,7 @@ def makeRests( timeRangeFromBarDuration=False, inPlace=False, hideRests=False, -) -> StreamType | None: +) -> StreamType|None: ''' Given a Stream with an offset not equal to zero, fill with one Rest preceding this offset. @@ -862,8 +862,8 @@ def makeRests( return returnObj def oHighTargetForMeasure( - m: stream.Measure | None = None, - ts: meter.TimeSignature | None = None + m: stream.Measure|None = None, + ts: meter.TimeSignature|None = None ) -> OffsetQL: ''' Needed for timeRangeFromBarDuration. @@ -889,7 +889,7 @@ def oHighTargetForMeasure( if isinstance(refStreamOrTimeRange, stream.Measure): oHighTarget = oHighTargetForMeasure(m=refStreamOrTimeRange) elif isinstance(refStreamOrTimeRange, meter.TimeSignature): - maybe_measure: stream.Measure | None = None + maybe_measure: stream.Measure|None = None if isinstance(returnObj.activeSite, stream.Measure): maybe_measure = returnObj.activeSite oHighTarget = oHighTargetForMeasure(m=maybe_measure, ts=refStreamOrTimeRange) @@ -920,7 +920,7 @@ def oHighTargetForMeasure( else: bundle = [returnObj] - lastTimeSignature: meter.TimeSignature | None = None + lastTimeSignature: meter.TimeSignature|None = None # bundle components may be voices, measures, or a flat Stream for component in bundle: oLow = component.lowestOffset @@ -992,7 +992,7 @@ def makeTies( inPlace=False, displayTiedAccidentals=False, classFilterList=(note.GeneralNote,), -) -> StreamType | None: +) -> StreamType|None: # noinspection PyShadowingNames ''' Given a stream containing measures, examine each element in the @@ -1365,7 +1365,7 @@ def makeTies( return None -def makeTupletBrackets(s: StreamType, *, inPlace=False) -> StreamType | None: +def makeTupletBrackets(s: StreamType, *, inPlace=False) -> StreamType|None: # noinspection PyShadowingNames ''' Given a flat Stream of mixed durations, designates the first and last tuplet of any group @@ -1407,7 +1407,7 @@ def makeTupletBrackets(s: StreamType, *, inPlace=False) -> StreamType | None: durationList.append(n.duration) # a list of (tuplet obj, Duration) pairs - tupletMap: list[tuple[duration.Tuplet | None, duration.Duration]] = [] + tupletMap: list[tuple[duration.Tuplet|None, duration.Duration]] = [] for dur in durationList: # all Duration objects tupletList = dur.tuplets @@ -1425,8 +1425,8 @@ def makeTupletBrackets(s: StreamType, *, inPlace=False) -> StreamType | None: # have a list of tuplet, Duration pairs completionCount: OffsetQL = 0.0 # qLen currently filled - completionTarget: OffsetQL | None = None # qLen necessary to fill tuplet - tupletPrevious: duration.Tuplet | None = None + completionTarget: OffsetQL|None = None # qLen necessary to fill tuplet + tupletPrevious: duration.Tuplet|None = None for i, (tupletObj, dur) in enumerate(tupletMap): if i < len(tupletMap) - 1: @@ -1583,7 +1583,7 @@ def moveNotesToVoices(source: StreamType, source.insert(0, dst) -def getTiePitchSet(prior: 'music21.note.NotRest') -> set[str] | None: +def getTiePitchSet(prior: 'music21.note.NotRest') -> set[str]|None: # noinspection PyShadowingNames,PyTypeChecker ''' helper method for makeAccidentals to get the tie pitch set (or None) @@ -1641,17 +1641,17 @@ def getTiePitchSet(prior: 'music21.note.NotRest') -> set[str] | None: return tiePitchSet def makeAccidentalsInMeasureStream( - s: StreamType | StreamIterator, + s: StreamType|StreamIterator, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - useKeySignature: bool | key.KeySignature = True, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + useKeySignature: bool|key.KeySignature = True, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, cautionaryNotImmediateRepeat: bool = True, - tiePitchSet: set[str] | None = None + tiePitchSet: set[str]|None = None ) -> None: ''' Makes accidentals in place on a stream that contains Measures. @@ -1678,7 +1678,7 @@ def makeAccidentalsInMeasureStream( # because we are definitely searching key signature contexts # only key.KeySignature values are interesting # but method arg is typed this way for backwards compatibility - ksLast: bool | key.KeySignature = False + ksLast: bool|key.KeySignature = False ksLastDiatonic: list[str] = [] if isinstance(useKeySignature, key.KeySignature): @@ -1762,12 +1762,12 @@ def ornamentalPitches(s: StreamType) -> list[pitch.Pitch]: return post def makeOrnamentalAccidentals( - noteOrChord: note.Note | chord.Chord, + noteOrChord: note.Note|chord.Chord, *, - pitchPast: list[pitch.Pitch] | None = None, - pitchPastMeasure: list[pitch.Pitch] | None = None, - otherSimultaneousPitches: list[pitch.Pitch] | None = None, - alteredPitches: list[pitch.Pitch] | None = None, + pitchPast: list[pitch.Pitch]|None = None, + pitchPastMeasure: list[pitch.Pitch]|None = None, + otherSimultaneousPitches: list[pitch.Pitch]|None = None, + alteredPitches: list[pitch.Pitch]|None = None, cautionaryPitchClass: bool = True, cautionaryAll: bool = False, overrideStatus: bool = False, @@ -1850,7 +1850,7 @@ def iterateBeamGroups( current_beam_group: list[note.NotRest] = [] in_beam_group: bool = False for el in iterator.notes: - first_el_type: str | None = None + first_el_type: str|None = None if el.beams and el.beams.getByNumber(1): first_el_type = el.beams.getTypeByNumber(1) @@ -1930,7 +1930,7 @@ def setStemDirectionOneGroup( has_consistent_stem_directions = False # noinspection PyTypeChecker - optional_clef_context: clef.Clef | None = group[0].getContextByClass(clef.Clef) + optional_clef_context: clef.Clef|None = group[0].getContextByClass(clef.Clef) if optional_clef_context is None: return clef_context: clef.Clef = optional_clef_context @@ -2001,7 +2001,7 @@ def splitElementsToCompleteTuplets( for container in iterator: general_notes = list(container.notesAndRests) - last_tuplet: duration.Tuplet | None = None + last_tuplet: duration.Tuplet|None = None partial_tuplet_sum = 0.0 for gn in general_notes: if ( @@ -2107,8 +2107,8 @@ def is_reexpressible(gn: note.GeneralNote) -> bool: reexpressible = [gn for gn in container.notesAndRests if is_reexpressible(gn)] to_consolidate: list[note.GeneralNote] = [] partial_tuplet_sum: OffsetQL = 0.0 - last_tuplet: duration.Tuplet | None = None - completion_target: OffsetQL | None = None + last_tuplet: duration.Tuplet|None = None + completion_target: OffsetQL|None = None for gn in reexpressible: prev_gn = gn.previous(note.GeneralNote, activeSiteOnly=True) if ( @@ -2173,7 +2173,7 @@ def saveAccidentalDisplayStatus(s) -> t.Generator[None, None, None]: * New in v9. ''' - displayStatuses: dict[int, bool | None] = {} + displayStatuses: dict[int, bool|None] = {} for p in s.pitches: if p.accidental is not None: displayStatuses[id(p)] = p.accidental.displayStatus diff --git a/music21/style.py b/music21/style.py index b3ef0b22de..c241ebc356 100644 --- a/music21/style.py +++ b/music21/style.py @@ -81,31 +81,31 @@ class Style(ProtoM21Object): def __init__(self) -> None: self.size = None - self.relativeX: float | int | None = None - self.relativeY: float | int | None = None - self.absoluteX: float | int | None = None + self.relativeX: float|int|None = None + self.relativeY: float|int|None = None + self.absoluteX: float|int|None = None # managed by property below. - self._absoluteY: float | int | None = None + self._absoluteY: float|int|None = None - self._enclosure: Enclosure | None = None + self._enclosure: Enclosure|None = None # how should this symbol be represented in the font? # SMuFL characters are allowed. self.fontRepresentation = None - self.color: str | None = None + self.color: str|None = None self.units: str = 'tenths' self.hideObjectOnPrint: bool = False - self.dashLength: float | int | None = None - self.spaceLength: float | int | None = None + self.dashLength: float|int|None = None + self.spaceLength: float|int|None = None - def _getEnclosure(self) -> Enclosure | None: + def _getEnclosure(self) -> Enclosure|None: return self._enclosure - def _setEnclosure(self, value: Enclosure | None): + def _setEnclosure(self, value: Enclosure|None): if value is None: self._enclosure = value elif value == Enclosure.NONE: @@ -272,9 +272,9 @@ class NoteStyle(Style): def __init__(self) -> None: super().__init__() - self.stemStyle: Style | None = None - self.accidentalStyle: Style | None = None - self.noteSize: str | None = None # can be 'cue' etc. + self.stemStyle: Style|None = None + self.accidentalStyle: Style|None = None + self.noteSize: str|None = None # can be 'cue' etc. class TextStyle(Style): @@ -364,7 +364,7 @@ def _setAlignHorizontal(self, value): @property - def justify(self) -> str | None: + def justify(self) -> str|None: ''' Get or set the justification. Valid values are left, center, right, full (not supported by MusicXML), and None @@ -384,7 +384,7 @@ def justify(self) -> str | None: return self._justify @justify.setter - def justify(self, value: str | None): + def justify(self, value: str|None): if value is None: self._justify = None else: @@ -393,7 +393,7 @@ def justify(self, value: str | None): self._justify = value.lower() @property - def fontStyle(self) -> str | None: + def fontStyle(self) -> str|None: ''' Get or set the style, as normal, italic, bold, and bolditalic. None is currently an acceptable value which should be "normal". @@ -413,7 +413,7 @@ def fontStyle(self) -> str | None: return self._fontStyle @fontStyle.setter - def fontStyle(self, value: str | None) -> None: + def fontStyle(self, value: str|None) -> None: if value is None: self._fontStyle = None else: @@ -628,8 +628,8 @@ class StyleMixin(common.SlottedObjectMixin): def __init__(self) -> None: # no need to call super().__init__() on SlottedObjectMixin # This might be dangerous though - self._style: Style | None = None - self._editorial: editorial.Editorial | None = None + self._style: Style|None = None + self._editorial: editorial.Editorial|None = None @property def hasStyleInformation(self) -> bool: diff --git a/music21/tablature.py b/music21/tablature.py index 63acf7e860..c452277e74 100644 --- a/music21/tablature.py +++ b/music21/tablature.py @@ -202,7 +202,7 @@ def getFretNoteByString(self, requestedString): return None - def getPitches(self) -> list[None | pitch.Pitch]: + def getPitches(self) -> list[None|pitch.Pitch]: ''' Returns a list of all the pitches (or None for each) given the FretNote information. This requires a tuning to be set. @@ -233,7 +233,7 @@ def getPitches(self) -> list[None | pitch.Pitch]: self.numStrings )) - pitchList: list[pitch.Pitch | None] = [None] * self.numStrings + pitchList: list[pitch.Pitch|None] = [None] * self.numStrings if not self.fretNotes: return pitchList diff --git a/music21/tempo.py b/music21/tempo.py index 6990c3f01d..8b98c9cd80 100644 --- a/music21/tempo.py +++ b/music21/tempo.py @@ -71,8 +71,8 @@ def convertTempoByReferent( - numberSrc: int | float, - quarterLengthBeatSrc: int | float, + numberSrc: int|float, + quarterLengthBeatSrc: int|float, quarterLengthBeatDst=1.0 ) -> float: ''' @@ -407,14 +407,14 @@ class MetronomeMark(TempoIndication): def __init__( self, - text: str | int | None = None, - number: OffsetQLIn | None = None, - referent: OffsetQLIn | str | duration.Duration | base.Music21Object | None = None, + text: str|int|None = None, + number: OffsetQLIn|None = None, + referent: OffsetQLIn|str|duration.Duration|base.Music21Object|None = None, *, parentheses: bool = False, playbackOnly: bool = False, - numberSounding: OffsetQLIn | None = None, - numberImplicit: bool | None = None, + numberSounding: OffsetQLIn|None = None, + numberImplicit: bool|None = None, **keywords ) -> None: super().__init__(**keywords) @@ -423,7 +423,7 @@ def __init__( number = text text = None - self._number: int | float | None = ( + self._number: int|float|None = ( common.numToIntOrFloat(number) if number is not None else None ) self.numberImplicit = None @@ -549,10 +549,10 @@ def _setText(self, value, updateNumberFromText=True): medium fast ''') - def _getNumber(self) -> int | float | None: + def _getNumber(self) -> int|float|None: return self._number # may be None - def _setNumber(self, value: int | float | None, + def _setNumber(self, value: int|float|None, updateTextFromNumber=True): # do not replace with a @property since _setNumber has an # optional second attribute. @@ -604,7 +604,7 @@ def _setNumberSounding(self, value): ''') # ------------------------------------------------------------------------- - def getQuarterBPM(self, useNumberSounding=True) -> float | None: + def getQuarterBPM(self, useNumberSounding=True) -> float|None: ''' Get a BPM value where the beat is a quarter; must convert from the defined beat to a quarter beat. Will return None if no beat number is defined. @@ -1180,8 +1180,8 @@ def setEqualityByReferent(self, side=None, referent=1.0): def setOtherByReferent( self, - side: str | None = None, - referent: str | int | float = 1.0 + side: str|None = None, + referent: str|int|float = 1.0 ): ''' Set the other side of the metric modulation not based on equality, diff --git a/music21/test/multiprocessTest.py b/music21/test/multiprocessTest.py index e26cc2df88..fa48454224 100644 --- a/music21/test/multiprocessTest.py +++ b/music21/test/multiprocessTest.py @@ -40,9 +40,9 @@ @dataclasses.dataclass class ModuleResponse: - returnCode: str | None = None + returnCode: str|None = None fp: t.Any = None - moduleName: str | None = None + moduleName: str|None = None success: t.Any = None testRunner: t.Any = None errors: t.Any = None diff --git a/music21/test/testSingleCoreAll.py b/music21/test/testSingleCoreAll.py index 1760ede4d8..3a0cc02846 100644 --- a/music21/test/testSingleCoreAll.py +++ b/music21/test/testSingleCoreAll.py @@ -39,7 +39,7 @@ def main(testGroup: Sequence[str] = ('test',), restoreEnvironmentDefaults=False, - limit: bool | None = None, + limit: bool|None = None, verbosity=2, show: bool = True, ): diff --git a/music21/text.py b/music21/text.py index ad58f53f62..953bd0ebbc 100644 --- a/music21/text.py +++ b/music21/text.py @@ -431,7 +431,7 @@ def __init__(self, text=None): self.text = text self.trigrams = _stored_trigrams.copy() or LanguageDetector.readExcerpts() - def mostLikelyLanguage(self, excerpt: str) -> str | None: + def mostLikelyLanguage(self, excerpt: str) -> str|None: # noinspection SpellCheckingInspection ''' Returns the code of the most likely language for a passage, works on diff --git a/music21/tinyNotation.py b/music21/tinyNotation.py index a706343c4f..c180abc486 100644 --- a/music21/tinyNotation.py +++ b/music21/tinyNotation.py @@ -273,7 +273,7 @@ class State: 2 ''' # expires after N tokens or never. - autoExpires: typing.Literal[False] | int = False + autoExpires: typing.Literal[False]|int = False def __init__(self, parent=None, stateInfo=None): self.affectedTokens = [] @@ -287,7 +287,7 @@ def start(self): ''' pass - def end(self) -> Music21Object | None: + def end(self) -> Music21Object|None: ''' called just after removing state ''' diff --git a/music21/tree/core.py b/music21/tree/core.py index 5bfc7431c4..530785d1b0 100644 --- a/music21/tree/core.py +++ b/music21/tree/core.py @@ -572,7 +572,7 @@ def populateFromSortedList(self, listOfTuples): '1' '0' ''' - def recurse(subListOfTuples) -> AVLNode | None: + def recurse(subListOfTuples) -> AVLNode|None: ''' Divide and conquer. ''' diff --git a/music21/tree/fromStream.py b/music21/tree/fromStream.py index 21978096fc..b56bb5e1cc 100644 --- a/music21/tree/fromStream.py +++ b/music21/tree/fromStream.py @@ -35,11 +35,11 @@ def listOfTreesByClass( inputStream: StreamType, *, classLists: Sequence[Sequence[type[M21ObjType]]] = (), - currentParentage: tuple[stream.Stream, ...] | None = None, + currentParentage: tuple[stream.Stream, ...]|None = None, initialOffset: float = 0.0, - flatten: bool | str = False, + flatten: bool|str = False, useTimespans: bool = False -) -> list[trees.OffsetTree | timespanTree.TimespanTree]: +) -> list[trees.OffsetTree|timespanTree.TimespanTree]: # noinspection PyShadowingNames r''' To be DEPRECATED in v8: this is no faster than calling streamToTimespanTree @@ -159,11 +159,11 @@ def listOfTreesByClass( def asTree( inputStream: StreamType, *, - flatten: t.Literal['semiFlat'] | bool = False, - classList: Sequence[type] | None = None, + flatten: t.Literal['semiFlat']|bool = False, + classList: Sequence[type]|None = None, useTimespans: bool = False, groupOffsets: bool = False -) -> trees.OffsetTree | trees.ElementTree | timespanTree.TimespanTree: +) -> trees.OffsetTree|trees.ElementTree|timespanTree.TimespanTree: ''' Converts a Stream and constructs an :class:`~music21.tree.trees.ElementTree` based on this. @@ -280,7 +280,7 @@ def recurseGetTreeByClass( if (inputStream.isSorted and groupOffsets is False # currently we can't populate for an OffsetTree* and (inputStream.isFlat or flatten is False)): - outputTree: trees.OffsetTree | trees.ElementTree = treeClass(source=inputStream) + outputTree: trees.OffsetTree|trees.ElementTree = treeClass(source=inputStream) return makeFastShallowTreeFromSortedStream(inputStream, outputTree=outputTree, classList=classList) @@ -292,9 +292,9 @@ def recurseGetTreeByClass( def makeFastShallowTreeFromSortedStream( inputStream: stream.Stream, *, - outputTree: trees.OffsetTree | trees.ElementTree, - classList: Sequence[type] | None = None, -) -> trees.OffsetTree | trees.ElementTree: + outputTree: trees.OffsetTree|trees.ElementTree, + classList: Sequence[type]|None = None, +) -> trees.OffsetTree|trees.ElementTree: ''' Use populateFromSortedList to quickly make a tree from a stream. @@ -319,8 +319,8 @@ def makeFastShallowTreeFromSortedStream( def asTimespans( inputStream, *, - flatten: str | bool = False, - classList: Sequence[type[Music21Object]] | None = None + flatten: str|bool = False, + classList: Sequence[type[Music21Object]]|None = None ) -> timespanTree.TimespanTree: r''' Recurses through a score and constructs a diff --git a/music21/tree/spans.py b/music21/tree/spans.py index f0f92007dc..aa0c33150c 100644 --- a/music21/tree/spans.py +++ b/music21/tree/spans.py @@ -325,16 +325,16 @@ class ElementTimespan(Timespan): def __init__( self, - element: base.Music21Object | None = None, - parentOffset: OffsetQLIn | None = None, - parentEndTime: OffsetQLIn | None = None, + element: base.Music21Object|None = None, + parentOffset: OffsetQLIn|None = None, + parentEndTime: OffsetQLIn|None = None, parentage: tuple[stream.Stream, ...] = (), - offset: OffsetQLIn | None = None, - endTime: OffsetQLIn | None = None, + offset: OffsetQLIn|None = None, + endTime: OffsetQLIn|None = None, ): super().__init__(offset=offset, endTime=endTime) - self.element: base.Music21Object | None = element + self.element: base.Music21Object|None = element self.parentage = parentage if parentOffset is not None: parentOffset = float(parentOffset) @@ -498,7 +498,7 @@ def part(self): from music21 import stream return self.getParentageByClass(classList=(stream.Part,)) - def makeElement(self, makeCopy: bool = True) -> base.Music21Object | None: + def makeElement(self, makeCopy: bool = True) -> base.Music21Object|None: ''' Return a copy of the element (or the same one if makeCopy is False) with the quarterLength set to the length of the timespan diff --git a/music21/tree/trees.py b/music21/tree/trees.py index 34d054f494..30b72debd9 100644 --- a/music21/tree/trees.py +++ b/music21/tree/trees.py @@ -96,7 +96,7 @@ class ElementTree(core.AVLTree): 6.0 ''' # TYPING # - rootNode: nodeModule.ElementNode | None + rootNode: nodeModule.ElementNode|None # CLASS VARIABLES # nodeClass = nodeModule.ElementNode @@ -553,7 +553,7 @@ def populateFromSortedList(self, listOfTuples): Indices:(l:197 *198* r:199) Payload:> ''' - def recurse(subListOfTuples, globalStartOffset) -> core.AVLNode | None: + def recurse(subListOfTuples, globalStartOffset) -> core.AVLNode|None: ''' Divide and conquer. ''' @@ -898,7 +898,7 @@ class OffsetTree(ElementTree): __slots__ = () # TYPING # - rootNode: nodeModule.OffsetNode | None + rootNode: nodeModule.OffsetNode|None nodeClass = nodeModule.OffsetNode diff --git a/music21/tree/verticality.py b/music21/tree/verticality.py index 7df4646b38..b0b5cfe830 100644 --- a/music21/tree/verticality.py +++ b/music21/tree/verticality.py @@ -337,7 +337,7 @@ def measureNumber(self): return self.startTimespans[0].measureNumber @property - def nextStartOffset(self) -> float | None: + def nextStartOffset(self) -> float|None: r''' Gets the next start-offset in the verticality's offset-tree. @@ -536,7 +536,7 @@ def startAndOverlapTimespans(self): return tuple(self.startTimespans[:] + self.overlapTimespans[:]) @property - def timeToNextEvent(self) -> OffsetQL | None: + def timeToNextEvent(self) -> OffsetQL|None: ''' Returns a float or Fraction of the quarterLength to the next event (usually the next Verticality, but also to the end of the piece). @@ -555,7 +555,7 @@ def timeToNextEvent(self) -> OffsetQL | None: def makeElement( self, - quarterLength: OffsetQLIn | None = None, + quarterLength: OffsetQLIn|None = None, *, addTies=True, addPartIdAsGroup=False, @@ -563,7 +563,7 @@ def makeElement( gatherArticulations='single', gatherExpressions='single', copyPitches=True, - ) -> note.Rest | chord.Chord: + ) -> note.Rest|chord.Chord: # noinspection PyDunderSlots, PyShadowingNames r''' Makes a Chord or Rest from this verticality and quarterLength. diff --git a/music21/variant.py b/music21/variant.py index f0f3254f52..30b3a528b9 100644 --- a/music21/variant.py +++ b/music21/variant.py @@ -97,7 +97,7 @@ def __init__( givenElements: t.Union[None, base.Music21Object, Sequence[base.Music21Object]] = None, - name: str | None = None, + name: str|None = None, givenElementsBehavior: GivenElementsBehavior = GivenElementsBehavior.OFFSETS, **music21ObjectKeywords, ): @@ -1368,8 +1368,8 @@ def mergePartAsOssia(mainPart, ossiaPart, ossiaName, def addVariant( s: stream.Stream, - startOffset: int | float, - sVariant: stream.Stream | Variant, + startOffset: int|float, + sVariant: stream.Stream|Variant, variantName=None, variantGroups=None, replacementDuration=None diff --git a/music21/voiceLeading.py b/music21/voiceLeading.py index c04d48ad58..b722b136aa 100644 --- a/music21/voiceLeading.py +++ b/music21/voiceLeading.py @@ -98,11 +98,11 @@ class VoiceLeadingQuartet(base.Music21Object): def __init__( self, - v1n1: None | str | note.Note | pitch.Pitch = None, - v1n2: None | str | note.Note | pitch.Pitch = None, - v2n1: None | str | note.Note | pitch.Pitch = None, - v2n2: None | str | note.Note | pitch.Pitch = None, - analyticKey: key.Key | None = None, + v1n1: None|str|note.Note|pitch.Pitch = None, + v1n2: None|str|note.Note|pitch.Pitch = None, + v2n1: None|str|note.Note|pitch.Pitch = None, + v2n2: None|str|note.Note|pitch.Pitch = None, + analyticKey: key.Key|None = None, **keywords ): super().__init__(**keywords) @@ -209,7 +209,7 @@ def key(self, keyValue): def _setVoiceNote( self, - value: None | str | note.Note | pitch.Pitch, + value: None|str|note.Note|pitch.Pitch, which: t.Literal['_v1n1', '_v1n2', '_v2n1', '_v2n2'] ): if value is None: @@ -230,10 +230,10 @@ def _setVoiceNote( f'not a valid note specification: {value!r}' ) from e - def _getV1n1(self) -> None | note.Note: + def _getV1n1(self) -> None|note.Note: return self._v1n1 - def _setV1n1(self, value: None | str | note.Note | pitch.Pitch): + def _setV1n1(self, value: None|str|note.Note|pitch.Pitch): self._setVoiceNote(value, '_v1n1') v1n1 = property(_getV1n1, _setV1n1, doc=''' @@ -244,10 +244,10 @@ def _setV1n1(self, value: None | str | note.Note | pitch.Pitch): ''') - def _getV1n2(self) -> None | note.Note: + def _getV1n2(self) -> None|note.Note: return self._v1n2 - def _setV1n2(self, value: None | str | note.Note | pitch.Pitch): + def _setV1n2(self, value: None|str|note.Note|pitch.Pitch): self._setVoiceNote(value, '_v1n2') v1n2 = property(_getV1n2, _setV1n2, doc=''' @@ -258,10 +258,10 @@ def _setV1n2(self, value: None | str | note.Note | pitch.Pitch): ''') - def _getV2n1(self) -> None | note.Note: + def _getV2n1(self) -> None|note.Note: return self._v2n1 - def _setV2n1(self, value: None | str | note.Note | pitch.Pitch): + def _setV2n1(self, value: None|str|note.Note|pitch.Pitch): self._setVoiceNote(value, '_v2n1') v2n1 = property(_getV2n1, _setV2n1, doc=''' @@ -272,10 +272,10 @@ def _setV2n1(self, value: None | str | note.Note | pitch.Pitch): ''') - def _getV2n2(self) -> None | note.Note: + def _getV2n2(self) -> None|note.Note: return self._v2n2 - def _setV2n2(self, value: None | str | note.Note | pitch.Pitch): + def _setV2n2(self, value: None|str|note.Note|pitch.Pitch): self._setVoiceNote(value, '_v2n2') v2n2 = property(_getV2n2, _setV2n2, doc=''' @@ -1441,7 +1441,7 @@ class Verticality(base.Music21Object): in a single part)''', } - def __init__(self, contentDict: dict | None = None, **keywords): + def __init__(self, contentDict: dict|None = None, **keywords): super().__init__(**keywords) if contentDict is None: contentDict = {} diff --git a/music21/volume.py b/music21/volume.py index 6ba4e1ef38..c61b326aa7 100644 --- a/music21/volume.py +++ b/music21/volume.py @@ -70,7 +70,7 @@ class Volume(prebase.ProtoM21Object, SlottedObjectMixin): def __init__( self, - client: note.NotRest | None = None, + client: note.NotRest|None = None, velocity=None, velocityScalar=None, velocityIsRelative=True, @@ -129,7 +129,7 @@ def mergeAttributes(self, other): self.velocityIsRelative = other.velocityIsRelative def getRealizedStr(self, - useDynamicContext: dynamics.Dynamic | bool = True, + useDynamicContext: dynamics.Dynamic|bool = True, useVelocity=True, useArticulations: t.Union[bool, articulations.Articulation, @@ -153,7 +153,7 @@ def getRealizedStr(self, def getRealized( self, - useDynamicContext: bool | dynamics.Dynamic = True, + useDynamicContext: bool|dynamics.Dynamic = True, useVelocity=True, useArticulations: t.Union[ bool, articulations.Articulation, Iterable[articulations.Articulation] From 9257549e9f2bf981aa65d4403585b7a0b859af91 Mon Sep 17 00:00:00 2001 From: Michael Scott Asato Cuthbert Date: Wed, 3 Jan 2024 00:10:01 -1000 Subject: [PATCH 2/3] fix typos --- music21/interval.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/music21/interval.py b/music21/interval.py index c4f77a5a60..60dc6b797d 100644 --- a/music21/interval.py +++ b/music21/interval.py @@ -432,7 +432,7 @@ def parseSpecifier(value: str|int|Specifier) -> Specifier: >>> interval.parseSpecifier('a') - This is not very useful, but there for completeness: + This is not very useful, but they are there for completeness: >>> interval.parseSpecifier(interval.Specifier.MAJOR) @@ -488,7 +488,7 @@ def parseSpecifier(value: str|int|Specifier) -> Specifier: def convertGeneric(value: int|str) -> int: ''' Convert an interval specified in terms of its name (second, third) - into an integer. If integers are passed, assume the are correct. + into an integer. If integers are passed, assume they are correct. >>> interval.convertGeneric(3) 3 @@ -639,7 +639,8 @@ def convertSemitoneToSpecifierGeneric(count: int|float) -> tuple[Specifier, int] (, 2) ''' # strip off microtone - return convertSemitoneToSpecifierGenericMicrotone(count)[:2] + specifier, semitones, _cent_offset = convertSemitoneToSpecifierGenericMicrotone(count) + return (specifier, semitones) _pythagorean_cache: dict[str, tuple[pitch.Pitch, Fraction]] = {} @@ -2480,7 +2481,7 @@ def transposePitch(self, p: pitch.Pitch, *, inPlace=False): >>> p5.ps 65.0 - Afterwards, spelling of the new pitch will always be inferred. + Afterward, the spelling of the new pitch will always be inferred. >>> p4.spellingIsInferred False @@ -3537,7 +3538,7 @@ def _diatonicTransposePitch(self, def reverse(self): ''' - Return an reversed version of this interval. + Return a reversed version of this interval. If :class:`~music21.pitch.Pitch` objects are stored as `pitchStart` and `pitchEnd`, these pitches are reversed. @@ -3827,7 +3828,7 @@ def getAbsoluteLowerNote(note1: note.Note|pitch.Pitch, def transposePitch( pitch1: pitch.Pitch, - interval1: str|interval, + interval1: str|Interval, *, inPlace=False ) -> pitch.Pitch: @@ -3880,7 +3881,7 @@ def transposePitch( def transposeNote( note1: note.Note, - intervalString: str|interval) -> note.Note: + intervalString: str|Interval) -> note.Note: ''' To be deprecated: call `n.transpose(intervalString)` directly. From f2a2f73e5d3442c4ac5b0f73c97fb3282556ae27 Mon Sep 17 00:00:00 2001 From: Michael Scott Asato Cuthbert Date: Wed, 3 Jan 2024 00:15:35 -1000 Subject: [PATCH 3/3] lint for m21 doesn't recongize _ as unused --- music21/interval.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music21/interval.py b/music21/interval.py index 60dc6b797d..abcd2f381a 100644 --- a/music21/interval.py +++ b/music21/interval.py @@ -639,7 +639,7 @@ def convertSemitoneToSpecifierGeneric(count: int|float) -> tuple[Specifier, int] (, 2) ''' # strip off microtone - specifier, semitones, _cent_offset = convertSemitoneToSpecifierGenericMicrotone(count) + specifier, semitones, unused_cent_offset = convertSemitoneToSpecifierGenericMicrotone(count) return (specifier, semitones)