Skip to content

Commit

Permalink
Merge pull request #1287 from cuthbertLab/mypy
Browse files Browse the repository at this point in the history
Continued work on mypy and better typing
  • Loading branch information
mscuthbert authored May 1, 2022
2 parents 5381ab6 + 2fa5a51 commit 79a8796
Show file tree
Hide file tree
Showing 110 changed files with 2,419 additions and 2,567 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pythonpylint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,4 @@ jobs:
- name: Type-check certain modules with mypy
run: |
mypy --follow-imports=silent music21/capella music21/common music21/corpus music21/features music21/figuredBass music21/humdrum music21/ipython21 music21/languageExcerpts music21/lily music21/mei music21/metadata music21/musedata music21/noteworthy music21/omr music21/romanText music21/test music21/vexflow
mypy --follow-imports=silent music21/articulations.py music21/bar.py music21/beam.py music21/clef.py music21/configure.py music21/defaults.py music21/derivation.py music21/duration.py music21/dynamics.py music21/editorial.py music21/environment.py music21/exceptions21.py music21/expressions.py music21/freezeThaw.py music21/harmony.py music21/instrument.py music21/interval.py music21/layout.py music21/percussion.py music21/prebase.py music21/repeat.py music21/roman.py music21/serial.py music21/sieve.py music21/sites.py music21/sorting.py music21/spanner.py music21/style.py music21/tablature.py music21/tempo.py music21/text.py music21/tie.py music21/tinyNotation.py music21/variant.py music21/voiceLeading.py music21/volpiano.py music21/volume.py
mypy --follow-imports=silent music21/articulations.py music21/bar.py music21/base.py music21/beam.py music21/clef.py music21/configure.py music21/defaults.py music21/derivation.py music21/duration.py music21/dynamics.py music21/editorial.py music21/environment.py music21/exceptions21.py music21/expressions.py music21/freezeThaw.py music21/harmony.py music21/instrument.py music21/interval.py music21/layout.py music21/percussion.py music21/prebase.py music21/repeat.py music21/roman.py music21/serial.py music21/sieve.py music21/sites.py music21/sorting.py music21/spanner.py music21/style.py music21/tablature.py music21/tempo.py music21/text.py music21/tie.py music21/tinyNotation.py music21/variant.py music21/voiceLeading.py music21/volpiano.py music21/volume.py
3 changes: 2 additions & 1 deletion documentation/testDocumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
from music21.test import testRunner


ModTuple = namedtuple('ModTuple', 'module fullModulePath moduleNoExtension autoGen')
ModTuple = namedtuple('ModTuple',
['module', 'fullModulePath', 'moduleNoExtension', 'autoGen'])


class Unbuffered:
Expand Down
66 changes: 32 additions & 34 deletions music21/abcFormat/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,20 @@
import unittest
import re

from music21 import articulations
from music21 import bar
from music21 import clef
from music21 import chord
from music21 import common
from music21 import environment
from music21 import exceptions21
from music21 import harmony
from music21 import meter
from music21 import stream
from music21 import tie
from music21 import articulations
from music21 import note
from music21 import chord
from music21 import spanner
from music21 import harmony
from music21 import stream
from music21 import tempo
from music21 import tie


environLocal = environment.Environment('abcFormat.translate')
Expand All @@ -52,7 +54,7 @@

def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):
'''
Handler conversion of a single Part of a multi-part score.
Handler conversion of a single Part of a Score with multiple Parts.
Results are added into the provided inputM21 object
or a newly created Part object
Expand All @@ -79,7 +81,7 @@ def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):
# one measure, that means that no measures are defined
barHandlers = abcHandler.splitByMeasure()
# environLocal.printDebug(['barHandlers', len(barHandlers)])
# merge loading meta data with each bar that precedes it
# merge loading metadata with each bar that precedes it
mergedHandlers = abcFormat.mergeLeadingMetaData(barHandlers)
# environLocal.printDebug(['mergedHandlers', len(mergedHandlers)])
else: # simply stick in a single list
Expand All @@ -92,14 +94,14 @@ def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):
useMeasures = True

# each unit in merged handlers defines possible a Measure (w/ or w/o metadata),
# trailing meta data, or a single collection of metadata and note data
# trailing metadata, or a single collection of metadata and note data

barCount = 0
measureNumber = 1
# merged handler are ABCHandlerBar objects, defining attributes for barlines

for mh in mergedHandlers:
# if use measures and the handler has notes; otherwise add to part
# if "use measures" is True and the handler has notes; otherwise add to part
# environLocal.printDebug(['abcToStreamPart', 'handler', 'left:', mh.leftBarToken,
# 'right:', mh.rightBarToken, 'len(mh)', len(mh)])

Expand All @@ -121,7 +123,7 @@ def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):
rbSpanners = spannerBundle.getByClass('RepeatBracket'
).getByCompleteStatus(False)
# this indication is most likely an opening, as ABC does
# not encode second ending ending boundaries
# not encode second ending boundaries
# we can still check thought:
if not rbSpanners:
# add this measure as a component
Expand Down Expand Up @@ -168,7 +170,7 @@ def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):

postTransposition, clefSet = parseTokens(mh, dst, p, useMeasures)

# append measure to part; in the case of trailing meta data
# append measure to part; in the case of trailing metadata
# dst may be part, even though useMeasures is True
if useMeasures and isinstance(dst, stream.Measure):
# check for incomplete bars
Expand All @@ -195,7 +197,7 @@ def abcToStreamPart(abcHandler, inputM21=None, spannerBundle=None):
except (ABCTranslateException, meter.MeterException, ZeroDivisionError):
pass
# clefs are not typically defined, but if so, are set to the first measure
# following the meta data, or in the open stream
# following the metadata, or in the open stream
if not clefSet and not p[clef.Clef]:
if useMeasures: # assume at start of measures
p.getElementsByClass(stream.Measure).first().clef = clef.bestClef(p, recurse=True)
Expand Down Expand Up @@ -390,7 +392,7 @@ def abcToStreamScore(abcHandler, inputM21=None):
else:
s = inputM21

# meta data can be first
# metadata can be first
md = metadata.Metadata()
s.insert(0, md)

Expand Down Expand Up @@ -448,7 +450,7 @@ def abcToStreamScore(abcHandler, inputM21=None):
return s

def abcToStreamOpus(abcHandler, inputM21=None, number=None):
'''Convert a multi-work stream into one or more complete works packed into a an Opus Stream.
'''Convert a multi-work stream into one or more complete works packed into an Opus Stream.
If a `number` argument is given, and a work is defined by
that number, that work is returned.
Expand All @@ -470,7 +472,7 @@ def abcToStreamOpus(abcHandler, inputM21=None, number=None):
scoreList = []
for key, value in sorted(abcDict.items()):
# do not need to set work number, as that will be gathered
# with meta data in abcToStreamScore
# with metadata in abcToStreamScore
try:
sc = abcToStreamScore(value)
scoreList.append(sc)
Expand All @@ -485,8 +487,8 @@ def abcToStreamOpus(abcHandler, inputM21=None, number=None):
return opus


# noinspection SpellCheckingInspection
def reBar(music21Part, *, inPlace=False):
# noinspection PyShadowingNames,SpellCheckingInspection
'''
Re-bar overflow measures using the last known time signature.
Expand All @@ -495,7 +497,6 @@ def reBar(music21Part, *, inPlace=False):
'Aililiu na Gamhna, S.35'
>>> music21Part = irl2[1]
The whole part is in 2/4 time, but there are some measures expressed in 4/4 time
without an explicit time signature change, an error in abc parsing due to the
omission of barlines. The method will split those measures such that they conform
Expand Down Expand Up @@ -664,11 +665,11 @@ def testChords(self):

# check pitches in chords; sharps are applied due to key signature
match = [p.nameWithOctave for p in s.parts[1].flatten().getElementsByClass(
'Chord')[4].pitches]
chord.Chord)[4].pitches]
self.assertEqual(match, ['F#4', 'D4', 'B3'])

match = [p.nameWithOctave for p in s.parts[1].flatten().getElementsByClass(
'Chord')[3].pitches]
chord.Chord)[3].pitches]
self.assertEqual(match, ['E4', 'C#4', 'A3'])

# s.show()
Expand Down Expand Up @@ -877,17 +878,15 @@ def testNoChord(self):
'''
score = converter.parse(target_str, format='abc')

self.assertEqual(len(list(score.flatten().getElementsByClass(
'ChordSymbol'))), 9)
self.assertEqual(len(list(score.flatten().getElementsByClass(
'NoChord'))), 4)
self.assertEqual(len(score[harmony.ChordSymbol]), 9)
self.assertEqual(len(score[harmony.NoChord]), 4)

score = harmony.realizeChordSymbolDurations(score)

self.assertEqual(8, score.getElementsByClass(harmony.ChordSymbol)[
-1].quarterLength)
self.assertEqual(4, score.getElementsByClass(harmony.ChordSymbol)[
0].quarterLength)
self.assertEqual(8, score.getElementsByClass(harmony.ChordSymbol)
.last().quarterLength)
self.assertEqual(4, score.getElementsByClass(harmony.ChordSymbol)
.first().quarterLength)

def testAbcKeyImport(self):
from music21 import abcFormat
Expand Down Expand Up @@ -944,15 +943,14 @@ def testRepeatBracketsA(self):
# s.show()
# one start, one end
# s.parts[0].show('t')
self.assertEqual(len(s['Repeat']), 2)
self.assertEqual(len(s[bar.Repeat]), 2)
# s.show()

# this has a 1 note pickup
# has three repeat bars; first one is implied
s = converter.parse(testFiles.draughtOfAle)
self.assertEqual(len(s['Repeat']), 3)
self.assertEqual(s.parts[0].getElementsByClass(
'Measure')[0].notes[0].pitch.nameWithOctave, 'D4')
self.assertEqual(len(s[bar.Repeat]), 3)
self.assertEqual(s[note.Note].first().pitch.nameWithOctave, 'D4')

# new problem case:
s = converter.parse(testFiles.hectorTheHero)
Expand All @@ -978,19 +976,19 @@ def testMetronomeMarkA(self):
from music21.abcFormat import testFiles
from music21 import converter
s = converter.parse(testFiles.fullRiggedShip)
mmStream = s.flatten().getElementsByClass('TempoIndication')
mmStream = s.flatten().getElementsByClass(tempo.TempoIndication)
self.assertEqual(len(mmStream), 1)
self.assertEqual(str(mmStream[0]), '<music21.tempo.MetronomeMark Quarter=100.0>')

s = converter.parse(testFiles.aleIsDear)
mmStream = s.flatten().getElementsByClass('TempoIndication')
mmStream = s.flatten().getElementsByClass(tempo.TempoIndication)
# this is a two-part pieces, and this is being added for each part
# not sure if this is a problem
self.assertEqual(len(mmStream), 2)
self.assertEqual(str(mmStream[0]), '<music21.tempo.MetronomeMark Quarter=211.0>')

s = converter.parse(testFiles.theBeggerBoy)
mmStream = s.flatten().getElementsByClass('TempoIndication')
mmStream = s[tempo.TempoIndication]
# this is a two-part pieces, and this is being added for each part
# not sure if this is a problem
self.assertEqual(len(mmStream), 1)
Expand Down
7 changes: 4 additions & 3 deletions music21/alpha/analysis/fixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
from music21 import stream

# noinspection PyShadowingBuiltins
_T = TypeVar('_T')

OMRMidiFixerType = TypeVar('OMRMidiFixerType', bound='OMRMidiFixer')

class OMRMidiFixer:
'''
Expand Down Expand Up @@ -392,7 +391,7 @@ def addOrnament(self,
return True
return False

def fix(self: _T, *, show=False, inPlace=True) -> Optional[_T]:
def fix(self: OMRMidiFixerType, *, show=False, inPlace=True) -> Optional[OMRMidiFixerType]:
'''
Corrects missed ornaments in omrStream according to midiStream
:param show: Whether to show results
Expand Down Expand Up @@ -443,6 +442,8 @@ def fix(self: _T, *, show=False, inPlace=True) -> Optional[_T]:

if not inPlace:
return TrillFixer(sa.changes, sa.targetStream, sa.sourceStream)
else:
return None

def getNotesWithinDuration(startingGeneralNote, totalDuration, referenceStream=None):
'''
Expand Down
6 changes: 5 additions & 1 deletion music21/alpha/analysis/testFiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
import os
import inspect

pathName = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
def _dummy():
pass # something for getting our path name


pathName = os.path.dirname(os.path.abspath(inspect.getfile(_dummy)))

K525_short_dir = pathName + os.sep + 'testfiles' + os.sep + 'K525'
K525_short_midi_path = K525_short_dir + os.sep + 'k525short_midi_ms_parsed.xml'
Expand Down
4 changes: 1 addition & 3 deletions music21/analysis/correlate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
from music21 import dynamics

from music21 import environment
_MOD = 'analysis.correlate'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.correlate')


# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -82,7 +81,6 @@ def _findActive(self, objNameSrc=None, objNameDst=None):
# dst object is within the source objects boundaries
# if so, append it to the source object's dictionary
for element in streamFlat.getElementsByClass(objNameDst):
# print(_MOD, 'dst', element)
dstStart = element.offset
dstEnd = dstStart + element.duration.quarterLength

Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@


from music21 import environment
_MOD = 'analysis.discrete'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.discrete')


# -----------------------------------------------------------------------------
Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/enharmonics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
from music21 import musedata

from music21 import environment
_MOD = 'analysis.enharmonics'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.enharmonics')


class EnharmonicsException(exceptions21.Music21Exception):
Expand Down
4 changes: 2 additions & 2 deletions music21/analysis/metrical.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
from music21 import stream

from music21 import environment
_MOD = "analysis.metrical"
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.metrical')


def labelBeatDepth(streamIn):
r'''
Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/neoRiemannian.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
from music21.analysis import enharmonics

from music21 import environment
_MOD = 'analysis.neoRiemannian'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.neoRiemannian')

# TODO: change doctests from passing on exceptions to raising them and trapping them.

Expand Down
2 changes: 1 addition & 1 deletion music21/analysis/reduceChordsOld.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def reduceThisMeasure(self, mI, measureIndex, maxChords, closedPosition, forceOc
cLastEnd = newOffset + cElCopy.quarterLength
m.coreInsert(newOffset, cElCopy, ignoreSort=True)

tsContext = mI.parts.first().getContextByClass('TimeSignature')
tsContext = mI.parts.first().getContextByClass(meter.TimeSignature)
if tsContext is not None:
if round(tsContext.barDuration.quarterLength - cLastEnd, 6) != 0.0:
cLast.quarterLength += tsContext.barDuration.quarterLength - cLastEnd
Expand Down
4 changes: 1 addition & 3 deletions music21/analysis/reduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@
from music21 import stream

from music21 import environment
_MOD = "analysis.reduction"
environLocal = environment.Environment(_MOD)

environLocal = environment.Environment('analysis.reduction')


# ------------------------------------------------------------------------------
Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/segmentByRests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@


from music21 import environment
_MOD = 'analysis.segmentByRests'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.segmentByRests')

# ------------------------------------------------------------------------------

Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/transposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
from music21 import chord

from music21 import environment
_MOD = 'analysis.transposition'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.transposition')


class TranspositionException(exceptions21.Music21Exception):
Expand Down
3 changes: 1 addition & 2 deletions music21/analysis/windowed.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@


from music21 import environment
_MOD = 'analysis.windowed'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('analysis.windowed')


# -----------------------------------------------------------------------------
Expand Down
3 changes: 1 addition & 2 deletions music21/articulations.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@
from music21 import environment
from music21 import style

_MOD = 'articulations'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('articulations')



Expand Down
3 changes: 1 addition & 2 deletions music21/audioSearch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@
from music21.audioSearch import transcriber

from music21 import environment
_MOD = 'audioSearch'
environLocal = environment.Environment(_MOD)
environLocal = environment.Environment('audioSearch')

audioChunkLength = 1024
recordSampleRate = 44100
Expand Down
Loading

0 comments on commit 79a8796

Please sign in to comment.