Skip to content

Commit

Permalink
Merge pull request #1679 from cuthbertLab/flake8-typing
Browse files Browse the repository at this point in the history
Styleguide Change - Union types
  • Loading branch information
mscuthbert authored Jan 3, 2024
2 parents e2ec77f + f2a2f73 commit 72120cc
Show file tree
Hide file tree
Showing 114 changed files with 1,448 additions and 1,445 deletions.
2 changes: 2 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion documentation/testDocumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
98 changes: 49 additions & 49 deletions music21/abcFormat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]] = {}


# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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():
Expand All @@ -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.
Expand Down Expand Up @@ -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('=')
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -947,7 +947,7 @@ def getBarObject(self) -> bar.Barline | None:
<music21.bar.Repeat direction=start>
'''
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)
Expand Down Expand Up @@ -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
'''
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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):
'''
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
'''
Expand Down Expand Up @@ -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.
Expand Down
Loading

0 comments on commit 72120cc

Please sign in to comment.