From dbd8c9f1e72b4a9df748daeefc2676c1b058bf26 Mon Sep 17 00:00:00 2001 From: Tim Beyer <35711942+TimFelixBeyer@users.noreply.github.com> Date: Mon, 4 Mar 2024 15:01:04 +0100 Subject: [PATCH] Fix pylint recommendations (#1694) Pylint now recommends using `yield from` and the use of `min/max` to simplify if statements. --- music21/analysis/reduceChords.py | 6 ++---- music21/analysis/reduceChordsOld.py | 3 +-- music21/analysis/windowed.py | 9 ++------- music21/braille/text.py | 18 ++++++------------ music21/common/objects.py | 3 +-- music21/features/jSymbolic.py | 3 +-- music21/figuredBass/realizer.py | 5 +---- music21/humdrum/spineParser.py | 3 +-- music21/musicxml/m21ToXml.py | 3 +-- music21/musicxml/xmlToM21.py | 3 +-- music21/scale/intervalNetwork.py | 12 ++++++------ music21/stream/base.py | 11 +++-------- music21/stream/iterator.py | 3 +-- music21/stream/makeNotation.py | 3 +-- music21/test/treeYield.py | 9 +++------ music21/tree/core.py | 6 ++---- music21/tree/node.py | 24 ++++++++---------------- music21/voiceLeading.py | 12 ++---------- 18 files changed, 43 insertions(+), 93 deletions(-) diff --git a/music21/analysis/reduceChords.py b/music21/analysis/reduceChords.py index 18121cddc2..6aaf44e5fe 100644 --- a/music21/analysis/reduceChords.py +++ b/music21/analysis/reduceChords.py @@ -384,8 +384,7 @@ def procedure(timespan): ) print(msg) # raise ChordReducerException(msg) - if offset < previousTimespan.endTime: - offset = previousTimespan.endTime + offset = max(offset, previousTimespan.endTime) scoreTree.removeTimespan(group[0]) subtree.removeTimespan(group[0]) newTimespan = group[0].new(offset=offset) @@ -542,8 +541,7 @@ def reduceMeasureToNChords( measureObject.flatten().notes, weightAlgorithm, ) - if maximumNumberOfChords > len(chordWeights): - maximumNumberOfChords = len(chordWeights) + maximumNumberOfChords = min(maximumNumberOfChords, len(chordWeights)) sortedChordWeights = sorted( chordWeights, key=chordWeights.get, diff --git a/music21/analysis/reduceChordsOld.py b/music21/analysis/reduceChordsOld.py index 8a76ee8627..886c2180d5 100644 --- a/music21/analysis/reduceChordsOld.py +++ b/music21/analysis/reduceChordsOld.py @@ -86,8 +86,7 @@ def reduceMeasureToNChords(self, chordWeights = self.computeMeasureChordWeights(mObj, weightAlgorithm) - if numChords > len(chordWeights): - numChords = len(chordWeights) + numChords = min(numChords, len(chordWeights)) maxNChords = sorted(chordWeights, key=chordWeights.get, reverse=True)[:numChords] if not maxNChords: diff --git a/music21/analysis/windowed.py b/music21/analysis/windowed.py index 58236939bf..1b1740baea 100644 --- a/music21/analysis/windowed.py +++ b/music21/analysis/windowed.py @@ -193,10 +193,8 @@ def analyze(self, windowSize, windowType='overlap'): elif windowType == 'noOverlap': start = 0 end = start + windowSize - i = 0 - while True: - if end >= len(self._windowedStream): - end = len(self._windowedStream) + for i in range(windowCount): + end = min(end, len(self._windowedStream)) current = stream.Stream() for j in range(start, end): @@ -210,9 +208,6 @@ def analyze(self, windowSize, windowType='overlap'): start = end end = start + windowSize - i += 1 - if i >= windowCount: - break elif windowType == 'adjacentAverage': # first get overlapping windows diff --git a/music21/braille/text.py b/music21/braille/text.py index c71d2398de..20d2d39ccb 100644 --- a/music21/braille/text.py +++ b/music21/braille/text.py @@ -336,8 +336,7 @@ def recenterHeadings(self): if self.allLines[i].isHeading: break lineLength = self.allLines[i].textLocation - if lineLength > maxLineLength: - maxLineLength = lineLength + maxLineLength = max(maxLineLength, lineLength) for j in range(indexStart, indexFinal): brailleTextLine = self.allLines[j] lineStrToCenter = str(brailleTextLine) @@ -565,12 +564,10 @@ def insert(self, textLocation, text): ''' if not self.canInsert(textLocation, text): raise BrailleTextException('Text cannot be inserted at specified location.') - self.textLocation = textLocation - for char in list(text): - self.allChars[self.textLocation] = char - self.textLocation += 1 - if self.textLocation > self.highestUsedLocation: - self.highestUsedLocation = self.textLocation + for i, char in enumerate(text, start=textLocation): + self.allChars[i] = char + self.textLocation = textLocation + len(text) + self.highestUsedLocation = max(self.highestUsedLocation, self.textLocation) def canAppend(self, text, addSpace=True): ''' @@ -600,10 +597,7 @@ def canAppend(self, text, addSpace=True): >>> btl.canAppend('1234', addSpace=False) False ''' - if self.highestUsedLocation > self.textLocation: - searchLocation = self.highestUsedLocation - else: - searchLocation = self.textLocation + searchLocation = max(self.highestUsedLocation, self.textLocation) addSpaceAmount = 1 if addSpace else 0 if (searchLocation + len(text) + addSpaceAmount) > self.lineLength: return False diff --git a/music21/common/objects.py b/music21/common/objects.py index 0816639f10..69fd7c7aec 100644 --- a/music21/common/objects.py +++ b/music21/common/objects.py @@ -67,8 +67,7 @@ class RelativeCounter(collections.Counter): def __iter__(self): sortedKeys = sorted(super().__iter__(), key=lambda x: self[x], reverse=True) - for k in sortedKeys: - yield k + yield from sortedKeys def items(self): for k in self: diff --git a/music21/features/jSymbolic.py b/music21/features/jSymbolic.py index 28746b69ca..37c666dee2 100644 --- a/music21/features/jSymbolic.py +++ b/music21/features/jSymbolic.py @@ -3016,8 +3016,7 @@ def process(self): for p in c.pitches: for gSub in p.groups: g.append(gSub) # add to temporary group; will act as a set - if len(g) > found: - found = len(g) + found = max(found, len(g)) self.feature.vector[0] = found diff --git a/music21/figuredBass/realizer.py b/music21/figuredBass/realizer.py index bd7d7fef17..ad606f1338 100644 --- a/music21/figuredBass/realizer.py +++ b/music21/figuredBass/realizer.py @@ -186,10 +186,7 @@ def addLyricsToBassNote(bassNote, notationString=None): n = notation.Notation(notationString) if not n.figureStrings: return - maxLength = 0 - for fs in n.figureStrings: - if len(fs) > maxLength: - maxLength = len(fs) + maxLength = max([len(fs) for fs in n.figureStrings]) for fs in n.figureStrings: spacesInFront = '' for i in range(maxLength - len(fs)): diff --git a/music21/humdrum/spineParser.py b/music21/humdrum/spineParser.py index ca33c51226..272ad8dd04 100644 --- a/music21/humdrum/spineParser.py +++ b/music21/humdrum/spineParser.py @@ -401,8 +401,7 @@ def parseEventListFromDataStream(self, dataStream=None): self.eventList.append(GlobalCommentLine(self.parsePositionInStream, line)) else: thisLine = SpineLine(self.parsePositionInStream, line) - if thisLine.numSpines > self.maxSpines: - self.maxSpines = thisLine.numSpines + self.maxSpines = max(self.maxSpines, thisLine.numSpines) self.eventList.append(thisLine) self.parsePositionInStream += 1 self.fileLength = self.parsePositionInStream diff --git a/music21/musicxml/m21ToXml.py b/music21/musicxml/m21ToXml.py index d6321e8013..ed24b107c4 100644 --- a/music21/musicxml/m21ToXml.py +++ b/music21/musicxml/m21ToXml.py @@ -1551,8 +1551,7 @@ def setPartsAndRefStream(self) -> None: else: innerStream.transferOffsetToElements() ht = innerStream.highestTime - if ht > self.highestTime: - self.highestTime = ht + self.highestTime = max(self.highestTime, ht) self.refStreamOrTimeRange = [0.0, self.highestTime] self.parts = list(s.parts) diff --git a/music21/musicxml/xmlToM21.py b/music21/musicxml/xmlToM21.py index bc2d7098d5..9c1ea70176 100644 --- a/music21/musicxml/xmlToM21.py +++ b/music21/musicxml/xmlToM21.py @@ -1967,8 +1967,7 @@ def xmlMeasureToMeasure(self, mxMeasure: ET.Element) -> stream.Measure: self.lastMeasureParser = measureParser - if measureParser.staves > self.maxStaves: - self.maxStaves = measureParser.staves + self.maxStaves = max(self.maxStaves, measureParser.staves) if measureParser.transposition is not None: self.updateTransposition(measureParser.transposition) diff --git a/music21/scale/intervalNetwork.py b/music21/scale/intervalNetwork.py index a42b5fac50..1ecff02bbb 100644 --- a/music21/scale/intervalNetwork.py +++ b/music21/scale/intervalNetwork.py @@ -828,8 +828,8 @@ def degreeMin(self): for n in self.nodes.values(): if x is None: x = n.degree - if n.degree < x: - x = n.degree + else: + x = min(x, n.degree) return x @property @@ -847,8 +847,8 @@ def degreeMax(self): for n in self.nodes.values(): if x is None: x = n.degree - if n.degree > x: - x = n.degree + else: + x = max(x, n.degree) return x @property @@ -870,8 +870,8 @@ def degreeMaxUnique(self): continue if x is None: x = n.degree - if n.degree > x: - x = n.degree + else: + x = max(x, n.degree) return x @property diff --git a/music21/stream/base.py b/music21/stream/base.py index 4dc799a1b3..e407600f69 100644 --- a/music21/stream/base.py +++ b/music21/stream/base.py @@ -2828,8 +2828,7 @@ def insertAndShift(self, offsetOrItemOrList, itemOrNone=None): o = insertList[i] e = insertList[i + 1] qL = e.duration.quarterLength - if o + qL > highestTimeInsert: - highestTimeInsert = o + qL + highestTimeInsert = max(highestTimeInsert, o + qL) if lowestOffsetInsert is None or o < lowestOffsetInsert: lowestOffsetInsert = o i += 2 @@ -8425,8 +8424,7 @@ def highestTime(self): for e in self._elements: candidateOffset = (self.elementOffset(e) + e.duration.quarterLength) - if candidateOffset > highestTimeSoFar: - highestTimeSoFar = candidateOffset + highestTimeSoFar = max(highestTimeSoFar, candidateOffset) self._cache['HighestTime'] = opFrac(highestTimeSoFar) return self._cache['HighestTime'] @@ -11183,10 +11181,7 @@ def makeVoices(self, *, inPlace=False, fillGaps=True): # environLocal.printDebug(['makeVoices(): olDict', olDict]) # find the max necessary voices by finding the max number # of elements in each group; these may not all be necessary - maxVoiceCount = 1 - for group in olDict.values(): - if len(group) > maxVoiceCount: - maxVoiceCount = len(group) + maxVoiceCount = max([len(group) for group in olDict.values()] + [1]) if maxVoiceCount == 1: # nothing to do here if not inPlace: return returnObj diff --git a/music21/stream/iterator.py b/music21/stream/iterator.py index 5c9bf2c40c..3991982fe7 100644 --- a/music21/stream/iterator.py +++ b/music21/stream/iterator.py @@ -508,8 +508,7 @@ def __contains__(self, item): def __reversed__(self): me = self.matchingElements() me.reverse() - for item in me: - yield item + yield from me def clone(self: StreamIteratorType) -> StreamIteratorType: ''' diff --git a/music21/stream/makeNotation.py b/music21/stream/makeNotation.py index f7f60b3dff..f9dc2a4ac7 100644 --- a/music21/stream/makeNotation.py +++ b/music21/stream/makeNotation.py @@ -523,8 +523,7 @@ def makeMeasures( refStreamHighestTime = refStreamOrTimeRange.highestTime else: # assume it's a list refStreamHighestTime = max(refStreamOrTimeRange) - if refStreamHighestTime > oMax: - oMax = refStreamHighestTime + oMax = max(oMax, refStreamHighestTime) # create a stream of measures to contain the offsets range defined # create as many measures as needed to fit in oMax diff --git a/music21/test/treeYield.py b/music21/test/treeYield.py index 89b2a76b03..eb8875165e 100644 --- a/music21/test/treeYield.py +++ b/music21/test/treeYield.py @@ -66,16 +66,14 @@ def run(self, obj, memo=None): dictTuple = ('dict', keyX) self.stackVals.append(dictTuple) x = obj[keyX] - for z in self.run(x, memo=memo): - yield z + yield from self.run(x, memo=memo) self.stackVals.pop() elif tObj in [list, tuple]: for i, x in enumerate(obj): listTuple = ('listLike', i) self.stackVals.append(listTuple) - for z in self.run(x, memo=memo): - yield z + yield from self.run(x, memo=memo) self.stackVals.pop() else: # objects or uncaught types... @@ -95,8 +93,7 @@ def run(self, obj, memo=None): objTuple = ('getattr', x) self.stackVals.append(objTuple) try: - for z in self.run(gotValue, memo=memo): - yield z + yield from self.run(gotValue, memo=memo) except RuntimeError: raise ValueError(f'Maximum recursion on:\n{self.currentLevel()}') self.stackVals.pop() diff --git a/music21/tree/core.py b/music21/tree/core.py index 530785d1b0..b1f12bf773 100644 --- a/music21/tree/core.py +++ b/music21/tree/core.py @@ -519,12 +519,10 @@ def __iter__(self): def recurse(node): if node is not None: if node.leftChild is not None: - for n in recurse(node.leftChild): - yield n + yield from recurse(node.leftChild) yield node if node.rightChild is not None: - for n in recurse(node.rightChild): - yield n + yield from recurse(node.rightChild) return recurse(self.rootNode) def populateFromSortedList(self, listOfTuples): diff --git a/music21/tree/node.py b/music21/tree/node.py index 2b7965e5ca..191543c4ba 100644 --- a/music21/tree/node.py +++ b/music21/tree/node.py @@ -273,18 +273,14 @@ def updateEndTimes(self): leftChild = self.leftChild if leftChild: leftChild.updateEndTimes() - if leftChild.endTimeLow < endTimeLow: - endTimeLow = leftChild.endTimeLow - if endTimeHigh < leftChild.endTimeHigh: - endTimeHigh = leftChild.endTimeHigh + endTimeLow = min(endTimeLow, leftChild.endTimeLow) + endTimeHigh = max(endTimeHigh, leftChild.endTimeHigh) rightChild = self.rightChild if rightChild: rightChild.updateEndTimes() - if rightChild.endTimeLow < endTimeLow: - endTimeLow = rightChild.endTimeLow - if endTimeHigh < rightChild.endTimeHigh: - endTimeHigh = rightChild.endTimeHigh + endTimeLow = min(endTimeLow, rightChild.endTimeLow) + endTimeHigh = max(endTimeHigh, rightChild.endTimeHigh) self.endTimeLow = endTimeLow self.endTimeHigh = endTimeHigh @@ -515,18 +511,14 @@ def updateEndTimes(self): leftChild = self.leftChild if leftChild: leftChild.updateEndTimes() - if leftChild.endTimeLow < endTimeLow: - endTimeLow = leftChild.endTimeLow - if endTimeHigh < leftChild.endTimeHigh: - endTimeHigh = leftChild.endTimeHigh + endTimeLow = min(endTimeLow, leftChild.endTimeLow) + endTimeHigh = max(endTimeHigh, leftChild.endTimeHigh) rightChild = self.rightChild if rightChild: rightChild.updateEndTimes() - if rightChild.endTimeLow < endTimeLow: - endTimeLow = rightChild.endTimeLow - if endTimeHigh < rightChild.endTimeHigh: - endTimeHigh = rightChild.endTimeHigh + endTimeLow = min(endTimeLow, rightChild.endTimeLow) + endTimeHigh = max(endTimeHigh, rightChild.endTimeHigh) self.endTimeLow = endTimeLow self.endTimeHigh = endTimeHigh diff --git a/music21/voiceLeading.py b/music21/voiceLeading.py index b722b136aa..ba6c9b5e41 100644 --- a/music21/voiceLeading.py +++ b/music21/voiceLeading.py @@ -1554,11 +1554,7 @@ def getShortestDuration(self): >>> vs1.getShortestDuration() 1.0 ''' - leastQuarterLength = self.objects[0].quarterLength - for obj in self.objects: - if obj.quarterLength < leastQuarterLength: - leastQuarterLength = obj.quarterLength - return leastQuarterLength + return min([obj.quarterLength for obj in self.objects]) def getLongestDuration(self): ''' @@ -1574,11 +1570,7 @@ def getLongestDuration(self): >>> vs1.getLongestDuration() 4.0 ''' - longestQuarterLength = self.objects[0].quarterLength - for obj in self.objects: - if obj.quarterLength > longestQuarterLength: - longestQuarterLength = obj.quarterLength - return longestQuarterLength + return max([obj.quarterLength for obj in self.objects]) def changeDurationOfAllObjects(self, newQuarterLength): '''