From fcdb67847c96ff0fb95138de7440b4951ddb7cc1 Mon Sep 17 00:00:00 2001 From: Michael Scott Asato Cuthbert Date: Fri, 21 Aug 2026 14:28:41 -1000 Subject: [PATCH 1/2] simplify bools --- documentation/docbuild/documenters.py | 4 +- .../usersGuide/usersGuide_20_examples2.ipynb | 2 +- music21/alpha/analysis/fixer.py | 14 +++---- music21/analysis/enharmonics.py | 6 +-- music21/analysis/neoRiemannian.py | 10 ++--- music21/analysis/reduction.py | 4 +- music21/audioSearch/recording.py | 5 ++- music21/audioSearch/scoreFollower.py | 4 +- music21/audioSearch/transcriber.py | 10 +++-- music21/chord/__init__.py | 4 +- music21/converter/subConverters.py | 6 +-- music21/defaults.py | 1 + music21/freezeThaw.py | 12 +++--- music21/graph/axis.py | 8 ++-- music21/instrument.py | 8 ++-- music21/key.py | 2 +- music21/musicxml/m21ToXml.py | 38 +++++++++---------- music21/note.py | 8 ++-- music21/repeat.py | 4 +- music21/search/base.py | 2 +- music21/stream/base.py | 8 +++- music21/stream/filters.py | 24 ++++++------ music21/stream/iterator.py | 8 ++-- music21/tree/verticality.py | 10 ++--- music21/variant.py | 26 ++++++------- 25 files changed, 118 insertions(+), 110 deletions(-) diff --git a/documentation/docbuild/documenters.py b/documentation/docbuild/documenters.py index 52cd94aaf9..b1043d6378 100644 --- a/documentation/docbuild/documenters.py +++ b/documentation/docbuild/documenters.py @@ -1564,13 +1564,13 @@ def getRstComposerWorksFormat(self, corpusWork): # worksAreVirtual = corpusWork.virtual # if worksAreVirtual: # workTitle += ' (*virtual*)' - if isSingleWork is False: + if not isSingleWork: result.append(workTitle) result.append('') procedure = self.getRstWorkFileDictFormat # if worksAreVirtual: # procedure = self.getRstVirtualWorkFileDictFormat - if isSingleWork is False: + if not isSingleWork: for corpusFile in corpusWork.files: result.extend(['- ' + procedure(corpusFile), '']) else: diff --git a/documentation/source/usersGuide/usersGuide_20_examples2.ipynb b/documentation/source/usersGuide/usersGuide_20_examples2.ipynb index 1ff52bcff0..23043c1113 100644 --- a/documentation/source/usersGuide/usersGuide_20_examples2.ipynb +++ b/documentation/source/usersGuide/usersGuide_20_examples2.ipynb @@ -703,7 +703,7 @@ " if analyzedKey.mode != 'minor':\n", " return False\n", " lastChord = getLastChord(score)\n", - " if lastChord.isMinorTriad() is False:\n", + " if not lastChord.isMinorTriad():\n", " return False\n", " if lastChord.root().name != analyzedKey.tonic.name:\n", " return False\n", diff --git a/music21/alpha/analysis/fixer.py b/music21/alpha/analysis/fixer.py index b69ae4df25..457ced740e 100644 --- a/music21/alpha/analysis/fixer.py +++ b/music21/alpha/analysis/fixer.py @@ -57,7 +57,7 @@ class DeleteFixer(OMRMidiFixer): def fix(self): super().fix() for (midiRef, omrRef, op) in self.changes: - if self.checkIfNoteInstance(midiRef, omrRef) is False: + if not self.checkIfNoteInstance(midiRef, omrRef): continue # if they are the same, don't bother to try changing it # 3 is the number of noChange Ops @@ -140,7 +140,7 @@ class EnharmonicFixer(OMRMidiFixer): >>> fixer3.fix() >>> omrNote3.pitch.accidental - TEST 4 (case 2-1) e.g MIDI = g#, ground truth = a-, OMR = an + TEST 4 (case 2-1) e.g. MIDI = g#, ground truth = a-, OMR = an >>> midiNote4 = note.Note('G#4') >>> omrNote4 = note.Note('An4') @@ -156,7 +156,7 @@ class EnharmonicFixer(OMRMidiFixer): >>> omrNote4.pitch.accidental - TEST 5 (case 2-2) e.g midi = g-, gt = f#, omr = fn + TEST 5 (case 2-2) e.g. midi = g-, gt = f#, omr = fn >>> midiNote5 = note.Note('G-4') >>> omrNote5 = note.Note('Fn4') @@ -237,7 +237,7 @@ def fix(self): for (midiRef, omrRef, op) in self.changes: omrRef.style.color = 'black' # if they're not notes, don't bother with rest - if self.checkIfNoteInstance(midiRef, omrRef) is False: + if not self.checkIfNoteInstance(midiRef, omrRef): continue # if they are the same, don't bother to try changing it # 3 is the number of noChange Ops @@ -253,7 +253,7 @@ def fix(self): omrRef.pitch.accidental = None else: # case 2-1: midi note is sharp, omr note is one step higher and natural, - # should be a flat instead. e.g midi = g#, gt = a-, omr = an + # should be a flat instead. e.g. midi = g#, gt = a-, omr = an # omr note has higher ps than midi-- on a higher # line or space than midi note if omrRef.pitch > midiRef.pitch: @@ -261,7 +261,7 @@ def fix(self): ).isEnharmonic(midiRef.pitch): omrRef.pitch.accidental = pitch.Accidental('flat') # case 2-2: midi note is flat, omr note is one step lower and natural, - # should be a flat instead. e.g midi = g-, gt = f#, omr = fn + # should be a flat instead. e.g. midi = g-, gt = f#, omr = fn # omr note has lower ps than midi-- on a higher line # or space than midi note elif omrRef.pitch < midiRef.pitch: @@ -399,7 +399,7 @@ def addOrnament(self, * show: True when note should be colored blue Returns True if added successfully, or False if there was already an - ornament on the note and it wasn't added. + ornament on the note, and it wasn't added. ''' if not any(isinstance(e, expressions.Ornament) for e in selectedNote.expressions): selectedNote.expressions.append(ornament) diff --git a/music21/analysis/enharmonics.py b/music21/analysis/enharmonics.py index 8cb66bf098..5f30c3cb86 100644 --- a/music21/analysis/enharmonics.py +++ b/music21/analysis/enharmonics.py @@ -99,7 +99,7 @@ def getAlterationScore(self, possibility): Returns a score according to the number of sharps and flats in a possible spelling. The score is the sum of the flats and sharps + 1, multiplied by the alterationPenalty. ''' - if self.ruleObject.alterationPenalty is False: + if not self.ruleObject.alterationPenalty: return 1 joinedPossibility = ''.join([p.name for p in possibility]) @@ -114,7 +114,7 @@ def getMixSharpFlatsScore(self, possibility): the score is given by the number of the lesser used accidental (sharps or flats) multiplied by the mixSharpsFlatsPenalty. ''' - if self.ruleObject.mixSharpsFlatsPenalty is False: + if not self.ruleObject.mixSharpsFlatsPenalty: return 1 joinedPossibility = ''.join([p.name for p in possibility]) @@ -128,7 +128,7 @@ def getAugDimScore(self, possibility): Returns a score based on the number of augmented and diminished intervals between successive pitches in the given spelling. ''' - if self.ruleObject.augDimPenalty is False: + if not self.ruleObject.augDimPenalty: return 1 intervalStr = '' diff --git a/music21/analysis/neoRiemannian.py b/music21/analysis/neoRiemannian.py index e16bb731c5..d610965cda 100644 --- a/music21/analysis/neoRiemannian.py +++ b/music21/analysis/neoRiemannian.py @@ -97,7 +97,7 @@ def L(c, raiseException=True): transposeInterval = 'm2' changingPitch = c.fifth else: - if raiseException is True: + if raiseException: raise LRPException('Cannot perform L on this chord: not a major or minor triad') return c @@ -134,7 +134,7 @@ def P(c, raiseException=True): transposeInterval = 'A1' changingPitch = c.third else: - if raiseException is True: + if raiseException: raise LRPException('Cannot perform P on this chord: not a Major or Minor triad') return c @@ -171,7 +171,7 @@ def R(c, raiseException=True): transposeInterval = '-M2' changingPitch = c.root() else: - if raiseException is True: + if raiseException: raise LRPException('Cannot perform R on this chord: not a Major or Minor triad') return c @@ -358,7 +358,7 @@ def LRP_combinations(c, ''' if not c.isMajorTriad() and not c.isMinorTriad(): # First to avoid doing anything else if fail - if raiseException is True: + if raiseException: raise LRPException( f'Cannot perform transformations on chord {c}: not a major or minor triad') return c @@ -435,7 +435,7 @@ def completeHexatonic(c, simplifyEnharmonics=False, raiseException=True): hexatonicList.append(lastChord) return hexatonicList else: - if raiseException is True: + if raiseException: raise LRPException( 'Cannot perform transformations on this chord: not a major or minor triad') diff --git a/music21/analysis/reduction.py b/music21/analysis/reduction.py index 56bbadb4c5..58befa6daa 100644 --- a/music21/analysis/reduction.py +++ b/music21/analysis/reduction.py @@ -1121,7 +1121,7 @@ def testPartReductionB(self, show=False): s.insert(0, p) pCount += 1 - if show is True: + if show: s.show() pr = analysis.reduction.PartReduction(s, normalize=False) @@ -1140,7 +1140,7 @@ def testPartReductionB(self, show=False): self._matchWeightedData(match, target) - if show is True: + if show: p = graph.plot.Dolan(s, title='Dynamics') p.run() diff --git a/music21/audioSearch/recording.py b/music21/audioSearch/recording.py index 4225b1397d..c390bd32bf 100644 --- a/music21/audioSearch/recording.py +++ b/music21/audioSearch/recording.py @@ -38,7 +38,8 @@ default_recordChunkLength = 1024 -def samplesFromRecording(seconds=10.0, storeFile=True, +def samplesFromRecording(seconds=10.0, + storeFile: bool = True, recordFormat=None, recordChannels=default_recordChannels, recordSampleRate=default_recordSampleRate, @@ -77,7 +78,7 @@ def samplesFromRecording(seconds=10.0, storeFile=True, st.close() p_audio.terminate() - if storeFile is not False: + if not storeFile: if isinstance(storeFile, str): waveFilename = storeFile else: diff --git a/music21/audioSearch/scoreFollower.py b/music21/audioSearch/scoreFollower.py index 2191fc02ae..5d6584957d 100644 --- a/music21/audioSearch/scoreFollower.py +++ b/music21/audioSearch/scoreFollower.py @@ -178,7 +178,7 @@ def repeatTranscription(self): # print('3') self.processing_time = time() - time_start environLocal.printDebug('and even to here.') - if END_OF_SCORE is True: + if END_OF_SCORE: exitType = 'endOfScore' # 'endOfScore' return exitType @@ -239,7 +239,7 @@ def silencePeriodDetection(self, notesList): if i.name != 'rest': onlyRests = False - if onlyRests is True: + if onlyRests: self.silencePeriod = True self.notesCounter = 0 self.silencePeriodCounter += 1 diff --git a/music21/audioSearch/transcriber.py b/music21/audioSearch/transcriber.py index 1f00e13f7e..d8ea6e799d 100644 --- a/music21/audioSearch/transcriber.py +++ b/music21/audioSearch/transcriber.py @@ -19,8 +19,12 @@ environLocal = environment.Environment('audioSearch.transcriber') -def runTranscribe(show=True, plot=True, useMic=True, - seconds=20.0, useScale=None, saveFile=True): # pragma: no cover +def runTranscribe(show: bool = True, + plot: bool = True, + useMic: bool = True, + seconds: float = 20.0, + useScale=None, + saveFile: bool|str = True): # pragma: no cover ''' runs all the methods to record from audio for `seconds` length (default 10.0) and transcribe the resulting melody returning a music21.Score object @@ -54,7 +58,7 @@ def runTranscribe(show=True, plot=True, useMic=True, waveFilename = saveFile # the rest of the score - if useMic is True: + if useMic: freqFromAQList = audioSearchBase.getFrequenciesFromMicrophone( length=seconds, storeWaveFilename=str(waveFilename)) diff --git a/music21/chord/__init__.py b/music21/chord/__init__.py index e024ed1909..d258b3746a 100644 --- a/music21/chord/__init__.py +++ b/music21/chord/__init__.py @@ -4005,7 +4005,7 @@ def semiClosedPosition( c2 = self.closedPosition(forceOctave=forceOctave, inPlace=inPlace, leaveRedundantPitches=leaveRedundantPitches) - if inPlace is True: + if inPlace: c2 = self # closedPosition() only returns None when inPlace=True, in which case c2 @@ -4028,7 +4028,7 @@ def semiClosedPosition( c2.clearCache() c2.sortAscending(inPlace=True) - if inPlace is False: + if not inPlace: return c2 def semitonesFromChordStep(self, chordStep, testRoot=None): diff --git a/music21/converter/subConverters.py b/music21/converter/subConverters.py index fd17db0a13..884167c492 100644 --- a/music21/converter/subConverters.py +++ b/music21/converter/subConverters.py @@ -100,7 +100,7 @@ def parseFile(self, loading the file and putting the data into parseData then there is no need to implement this method. Just set self.readBinary to True | False. ''' - if self.readBinary is False: + if not self.readBinary: import locale with open(filePath, encoding=locale.getpreferredencoding()) as f: dataStream = f.read() @@ -289,7 +289,7 @@ def writeDataStream(self, if fp is None: fp = self.getTemporaryFile() - if self.readBinary is False: + if not self.readBinary: writeFlags = 'w' else: writeFlags = 'wb' @@ -330,7 +330,7 @@ def toData( and return the object (str or bytes) returned. ''' fp = self.write(obj, fmt=fmt, subformats=subformats, **keywords) - if self.readBinary is False: + if not self.readBinary: readFlags = 'r' else: readFlags = 'rb' diff --git a/music21/defaults.py b/music21/defaults.py index 89c09a0557..4e41c2ef6a 100644 --- a/music21/defaults.py +++ b/music21/defaults.py @@ -17,6 +17,7 @@ import typing as t from music21 import _version + # note: this module should not import any higher level modules type StepName = t.Literal['C', 'D', 'E', 'F', 'G', 'A', 'B'] # restating so as not to import. diff --git a/music21/freezeThaw.py b/music21/freezeThaw.py index afef17f046..86cf877fee 100644 --- a/music21/freezeThaw.py +++ b/music21/freezeThaw.py @@ -210,7 +210,7 @@ def __init__(self, streamObj=None, fastButUnsafe=False, topLevel=True, streamIds self.subStreamFreezers = {} # this will keep track of sub freezers for spanners - if streamObj is not None and fastButUnsafe is False: + if streamObj is not None and not fastButUnsafe: # deepcopy necessary because we mangle sites in the objects # before serialization self.stream = copy.deepcopy(streamObj) @@ -267,7 +267,7 @@ def setupSerializationScaffold(self, streamObj=None): # might not work when recurse yields allEls = list(streamObj.recurse(restoreActiveSites=False)) - if self.topLevel is True: + if self.topLevel: self.findActiveStreamIdsInHierarchy(streamObj) for el in allEls: @@ -297,7 +297,7 @@ def setupSerializationScaffold(self, streamObj=None): # removing seems to create problems for jsonPickle with Spanners self.setupStoredElementOffsetTuples(streamObj) - if self.topLevel is True: + if self.topLevel: self.recursiveClearSites(streamObj) def removeStreamStatusClient(self, streamObj): @@ -578,11 +578,11 @@ def findActiveStreamIdsInHierarchy( includeSelf=True) streamIds = [id(s) for s in streamsFoundGenerator] - if getSpanners is True: + if getSpanners: spannerBundle = streamObj.spannerBundle streamIds += spannerBundle.getSpannerStorageIds() - if getVariants is True: + if getVariants: for el in streamObj.recurse(includeSelf=True).getElementsByClass(variant.Variant): streamIds += self.findActiveStreamIdsInHierarchy(el._stream) @@ -853,7 +853,7 @@ def restoreElementsFromTuples(self, streamObj): streamObj.coreElementsChanged() for subElement in streamObj: - if subElement.isStream is True: + if subElement.isStream: # note that the elements may have already been restored # if the spanner stores a part or something in the Stream # for instance in a StaffGroup object diff --git a/music21/graph/axis.py b/music21/graph/axis.py index d35833ec60..30630ebd85 100644 --- a/music21/graph/axis.py +++ b/music21/graph/axis.py @@ -317,7 +317,7 @@ class PitchAxis(Axis): def __init__(self, client=None, axisName='x'): super().__init__(client, axisName) - self.showOctaves = 'few' + self.showOctaves: bool|t.Literal['few'] = 'few' self.showEnharmonic = True self.blankLabelUnused = True self.hideUnused = True @@ -425,7 +425,7 @@ def unweightedSortHelper(x): sub.append(accidentalLabelToUnicode(name)) label = '/'.join(sub) - if self.showOctaves is False: + if not self.showOctaves: label = re.sub(r'\d', '', label) elif self.showOctaves == 'few': matchOctave = re.search(r'\d', label) @@ -451,7 +451,7 @@ class PitchClassAxis(PitchAxis): quantities: tuple[str, ...] = ('pitchClass', 'pitchclass', 'pc') def __init__(self, client=None, axisName='x'): - self.showOctaves = False + self.showOctaves: bool|t.Literal['few'] = False super().__init__(client, axisName) self.minValue = 0 self.maxValue = 11 @@ -1129,7 +1129,7 @@ class QuarterLengthAxis(PositionAxis): def __init__(self, client=None, axisName='x'): super().__init__(client, axisName) - self.useLogScale = True + self.useLogScale: bool|int = True self.useDurationNames = False def extractOneElement(self, n, formatDict): diff --git a/music21/instrument.py b/music21/instrument.py index 24a61261ec..799d5c1a8a 100644 --- a/music21/instrument.py +++ b/music21/instrument.py @@ -65,7 +65,7 @@ def unbundleInstruments(streamIn: stream.Stream, {1.0} {1.0} ''' - if inPlace is True: + if inPlace: s = streamIn else: s = streamIn.coreCopyAsDerivation('unbundleInstruments') @@ -78,7 +78,7 @@ def unbundleInstruments(streamIn: stream.Stream, off = thisObj.offset s.insert(off, i) - if inPlace is False: + if not inPlace: return s @@ -106,7 +106,7 @@ def bundleInstruments(streamIn: stream.Stream, Cowbell ''' - if inPlace is True: + if inPlace: s = streamIn else: s = streamIn.coreCopyAsDerivation('bundleInstruments') @@ -120,7 +120,7 @@ def bundleInstruments(streamIn: stream.Stream, elif isinstance(thisObj, note.NotRest): thisObj.storedInstrument = lastInstrument - if inPlace is False: + if not inPlace: return s diff --git a/music21/key.py b/music21/key.py index 12f285f2f0..6085d9a4d3 100644 --- a/music21/key.py +++ b/music21/key.py @@ -1295,7 +1295,7 @@ def transpose(self, >>> changingKey ''' - if inPlace is True: + if inPlace: super().transpose(value, inPlace=inPlace) post = self else: diff --git a/music21/musicxml/m21ToXml.py b/music21/musicxml/m21ToXml.py index 5098428eb1..24ef075cf6 100644 --- a/music21/musicxml/m21ToXml.py +++ b/music21/musicxml/m21ToXml.py @@ -795,7 +795,7 @@ def setStyleAttributes(self, mxObject, m21Object, musicXMLNames, m21Names=None): ''' if isinstance(m21Object, style.Style): stObj = m21Object - elif m21Object.hasStyleInformation is False: + elif not m21Object.hasStyleInformation: return else: stObj = m21Object.style @@ -1000,7 +1000,7 @@ def setEditorial(self, mxObject, m21Object): hello ''' - if m21Object.hasEditorialInformation is False: + if not m21Object.hasEditorialInformation: return # MusicXML allows only one footnote or level, so we take the first. @@ -2186,9 +2186,9 @@ def staffGroupToXmlPartGroup(self, staffGroup): self.setPosition(mxGroupSymbol, staffGroup) mxGroupBarline = SubElement(mxPartGroup, 'group-barline') - if staffGroup.barTogether is True: + if staffGroup.barTogether is True: # not a bool. mxGroupBarline.text = 'yes' - elif staffGroup.barTogether is False: + elif staffGroup.barTogether is False: # not a bool. mxGroupBarline.text = 'no' elif staffGroup.barTogether == 'Mensurstrich': mxGroupBarline.text = 'Mensurstrich' @@ -2268,7 +2268,7 @@ def setIdentification(self) -> Element: self.mxIdentification = mxId # creators - foundOne = False + foundOne: bool = False if self.scoreMetadata is not None: # We ignore the name ('namespace:name') here, and use # c.role instead so we can represent non-standard roles. @@ -2282,7 +2282,7 @@ def setIdentification(self) -> Element: mxId.append(mxCreator) foundOne = True - if foundOne is False and defaults.author: + if not foundOne and defaults.author: mxCreator = SubElement(mxId, 'creator') mxCreator.set('type', 'composer') mxCreator.text = defaults.author @@ -3417,12 +3417,12 @@ def parseOneElement( parsedObject = True break - if parsedObject is False: + if not parsedObject: for className in classes: if className in self.ignoreOnParseClasses: parsedObject = True break - if parsedObject is False: + if not parsedObject: environLocal.printDebug(['did not convert object', obj]) else: # appendSpanners == AppendSpanners.RELATED_ONLY @@ -3812,10 +3812,10 @@ def objectAttachedSpannersToNotations( isFirstOrLast = True # print('Trill is last') - if isFirstOrLast is False: + if not isFirstOrLast: continue # do not put a wavy-line tag on mid-trill notes ornaments.append(mxWavyLine) - if isFirstANDLast is True: + if isFirstANDLast: # make another one: mxWavyLine = Element('wavy-line') mxWavyLine.set('number', str(su.idLocal)) @@ -4034,7 +4034,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): TODO: Test with spanners ''' - addChordTag = (noteIndexInChord != 0) + addChordTag: bool = (noteIndexInChord != 0) setb = setAttributeFromAttribute mxNote = Element('note') @@ -4106,7 +4106,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): elif n.isRest: SubElement(mxNote, 'rest') - if d.isGrace is not True: + if d.isGrace: mxDuration = self.durationXml(d) mxNote.append(mxDuration) # divisions only @@ -4168,7 +4168,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): stemDirection = None # if we are not in a chord, or we are the first note of a chord, get stem # direction from the chordOrNote object - if (addChordTag is False + if (not addChordTag and isinstance(chordOrN, note.NotRest) and chordOrN.stemDirection != 'unspecified'): chordOrN = t.cast(note.NotRest, chordOrN) @@ -4211,7 +4211,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): # TODO: notehead-text # beam - if addChordTag is False: + if not addChordTag: if isinstance(chordOrN, note.NotRest) and chordOrN.beams is not None: nBeamsList = self.beamsToXml(chordOrN.beams) for mxB in nBeamsList: @@ -4220,7 +4220,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): mxNotationsList = self.noteToNotations(n, noteIndexInChord, chordParent) # add tuplets if it's a note or the first of a chord. - if addChordTag is False: + if not addChordTag: for i, tup in enumerate(d.tuplets): tupTagList = self.tupletToXmlTuplet(tup, i + 1) mxNotationsList.extend(tupTagList) @@ -4231,7 +4231,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): mxNotations.append(mxN) # lyric - if addChordTag is False: + if not addChordTag: for lyricObj in chordOrN.lyrics: if lyricObj.text is None: continue # happens sometimes! @@ -4815,7 +4815,7 @@ def dealWithNotehead( Returns nothing. The mxNote is modified in place. ''' - foundANotehead = False + foundANotehead: bool = False if (isinstance(n, note.NotRest) and (n.notehead != 'normal' or n.noteheadParenthesis @@ -4825,7 +4825,7 @@ def dealWithNotehead( foundANotehead = True mxNotehead = self.noteheadToXml(n) mxNote.append(mxNotehead) - if foundANotehead is False and chordParent is not None: + if not foundANotehead and chordParent is not None: if (hasattr(chordParent, 'notehead') and (chordParent.notehead != 'normal' or chordParent.noteheadParenthesis @@ -5737,7 +5737,7 @@ def noChordToXml(self, cs: harmony.NoChord) -> Element: quarter ''' - if cs.writeAsChord is True: + if cs.writeAsChord: r = note.Rest(duration=cs.duration) return self.restToXml(r) diff --git a/music21/note.py b/music21/note.py index 7a2ac2d9fb..aaed8c01d5 100644 --- a/music21/note.py +++ b/music21/note.py @@ -542,13 +542,13 @@ def setTextAndSyllabic(self, rawText: str, applyRaw: bool = False) -> None: rawText = str(rawText) # check for hyphens - if applyRaw is False and rawText.startswith('-') and not rawText.endswith('-'): + if not applyRaw and rawText.startswith('-') and not rawText.endswith('-'): self.text = rawText[1:] self.syllabic = 'end' - elif applyRaw is False and not rawText.startswith('-') and rawText.endswith('-'): + elif not applyRaw and not rawText.startswith('-') and rawText.endswith('-'): self.text = rawText[:-1] self.syllabic = 'begin' - elif applyRaw is False and rawText.startswith('-') and rawText.endswith('-'): + elif not applyRaw and rawText.startswith('-') and rawText.endswith('-'): self.text = rawText[1:-1] self.syllabic = 'middle' else: # assume single @@ -823,7 +823,7 @@ def addLyric(self, thisLyric.text = text foundLyric = True break - if foundLyric is False: + if not foundLyric: self.lyrics.append(Lyric(text, lyricNumber, applyRaw=applyRaw, identifier=lyricIdentifier)) diff --git a/music21/repeat.py b/music21/repeat.py index 02f614b23a..22dca1761a 100644 --- a/music21/repeat.py +++ b/music21/repeat.py @@ -452,7 +452,7 @@ def insertRepeatEnding(s, start, end, endingNumber: int = 1, *, inPlace=False): rbOffset = measures[0].getOffsetBySite(s) s.insert(rbOffset, rb) - if inPlace is True: + if inPlace: return else: return s @@ -774,7 +774,7 @@ def process(self, deepcopy: bool = True) -> StreamType: # need to copy source measures, as may later measures before copying # them, and this can result in orphaned spanners - if deepcopy is not False: + if deepcopy: srcStream = self._srcMeasureStream.coreCopyAsDerivation('expandRepeats') else: srcStream = self._srcMeasureStream diff --git a/music21/search/base.py b/music21/search/base.py index c69485b352..b111c9197b 100644 --- a/music21/search/base.py +++ b/music21/search/base.py @@ -267,7 +267,7 @@ def run(self) -> list[SearchMatch]: break if result is False: break - if result is True: + if result: result = None if result is not False: diff --git a/music21/stream/base.py b/music21/stream/base.py index a44db74e67..121bcc0bfd 100644 --- a/music21/stream/base.py +++ b/music21/stream/base.py @@ -351,7 +351,7 @@ def __init__(self, self._atSoundingPitch: bool|t.Literal['unknown'] = 'unknown' # experimental - self._mutable = True + self._mutable: bool = True if givenElements is None: return @@ -8295,7 +8295,7 @@ def makeImmutable(self): Clean this Stream: for self and all elements, purge all dead locations and remove all non-contained sites. Further, restore all active sites. ''' - if self._mutable is not False: + if self._mutable: self.sort() # must sort before making immutable for e in self.recurse(streamsOnly=True, includeSelf=False): # e.purgeLocations(rescanIsDead=True) @@ -8308,6 +8308,10 @@ def makeImmutable(self): self._mutable = False def makeMutable(self, recurse=True): + ''' + Soft-Deprecated -- this will return a New Stream at some point -- + once immutable, never mutable. + ''' self._mutable = True if recurse: for e in self.recurse(streamsOnly=True): diff --git a/music21/stream/filters.py b/music21/stream/filters.py index ef13f1e491..aee1f5553f 100644 --- a/music21/stream/filters.py +++ b/music21/stream/filters.py @@ -361,15 +361,13 @@ def __init__(self, super().__init__() self.offsetStart = opFrac(offsetStart) + self.zeroLengthSearch: bool = True if offsetEnd is None: self.offsetEnd = offsetStart - self.zeroLengthSearch = True else: self.offsetEnd = opFrac(offsetEnd) if offsetEnd > offsetStart: self.zeroLengthSearch = False - else: - self.zeroLengthSearch = True self.mustFinishInSpan = mustFinishInSpan self.mustBeginInSpan = mustBeginInSpan @@ -432,35 +430,35 @@ def isElementOffsetInRange(self, e, offset, *, stopAfterEnd=False) -> bool: else: elementIsZeroLength = False - if self.zeroLengthSearch is True and elementIsZeroLength is True: + if self.zeroLengthSearch and elementIsZeroLength: # zero Length Searches -- include all zeroLengthElements return True - if self.mustFinishInSpan is True: + if self.mustFinishInSpan: if elementEnd > self.offsetEnd: # environLocal.warn([elementEnd, offsetEnd, e]) return False - if self.includeEndBoundary is False: + if not self.includeEndBoundary: # we include the end boundary if the search is zeroLength -- # otherwise nothing can be retrieved if elementEnd == self.offsetEnd: return False - if self.mustBeginInSpan is True: + if self.mustBeginInSpan: if offset < self.offsetStart: return False - if self.includeEndBoundary is False and offset == self.offsetEnd: + if not self.includeEndBoundary and offset == self.offsetEnd: return False - elif (elementIsZeroLength is False + elif (not elementIsZeroLength and elementEnd == self.offsetEnd - and self.zeroLengthSearch is True): + and self.zeroLengthSearch): return False - if self.includeEndBoundary is False and offset == self.offsetEnd: + if not self.includeEndBoundary and offset == self.offsetEnd: return False - if self.includeElementsThatEndAtStart is False and elementEnd == self.offsetStart: + if not self.includeElementsThatEndAtStart and elementEnd == self.offsetStart: return False return True @@ -473,7 +471,7 @@ class OffsetHierarchyFilter(OffsetFilter): Finds elements that match a given offset range in the hierarchy. - Do not call .stream() afterwards or unstable results can occur. + Do not call .stream() afterward or unstable results can occur. ''' derivationStr = 'getElementsByOffsetInHierarchy' diff --git a/music21/stream/iterator.py b/music21/stream/iterator.py index 238ffff890..95118c114a 100644 --- a/music21/stream/iterator.py +++ b/music21/stream/iterator.py @@ -204,10 +204,10 @@ def __next__(self) -> M21ObjType: continue self.elementIndex += 1 - if self.matchesFilters(e) is False: + if not self.matchesFilters(e): continue - if self.restoreActiveSites is True: + if self.restoreActiveSites: self.srcStream.coreSelfActiveSite(e) self.updateActiveInformation() @@ -1827,10 +1827,10 @@ def __next__(self) -> M21ObjType: childRecursiveIterator.iteratorStartOffsetInHierarchy = newStartOffset self.childRecursiveIterator = childRecursiveIterator - if self.matchesFilters(e) is False: + if not self.matchesFilters(e): continue - if self.restoreActiveSites is True: + if self.restoreActiveSites: self.srcStream.coreSelfActiveSite(e) self.updateActiveInformation() diff --git a/music21/tree/verticality.py b/music21/tree/verticality.py index b37257bb66..789d6466a6 100644 --- a/music21/tree/verticality.py +++ b/music21/tree/verticality.py @@ -1051,7 +1051,7 @@ def getAllVoiceLeadingQuartets( if not hasattr(pairedMotion[0][0], 'pitches'): continue # not a PitchedTimespan - if includeNoMotion is False: + if not includeNoMotion: if (pairedMotion[0][0].pitches == pairedMotion[0][1].pitches and pairedMotion[1][0].pitches == pairedMotion[1][1].pitches): continue @@ -1070,7 +1070,7 @@ def getAllVoiceLeadingQuartets( if not isAppropriate: continue - if returnObjects is False: + if not returnObjects: filteredList.append(pairedMotion) else: n11 = pairedMotion[0][0].element @@ -1160,15 +1160,15 @@ def getPairedMotion( if previousTs is None or not isinstance(previousTs, spans.PitchedTimespan): continue # first not in piece in this part - if includeRests is False: + if not includeRests: if previousTs not in stopTss: continue - if includeOblique is False and startingTs.pitches == previousTs.pitches: + if not includeOblique and startingTs.pitches == previousTs.pitches: continue tsTuple = (previousTs, startingTs) allPairedMotions.append(tsTuple) - if includeOblique is True: + if includeOblique: for overlapTs in overlapTss: if not isinstance(overlapTs, spans.PitchedTimespan): continue diff --git a/music21/variant.py b/music21/variant.py index cf1f6ae392..9adbfd2a41 100644 --- a/music21/variant.py +++ b/music21/variant.py @@ -773,7 +773,7 @@ def mergeVariantScores(aScore, vScore, variantName='variant', *, inPlace=False): raise VariantException( 'These scores do not have the same number of parts and cannot be merged.') - if inPlace is True: + if inPlace: returnObj = aScore else: returnObj = aScore.coreCopyAsDerivation('mergeVariantScores') @@ -781,7 +781,7 @@ def mergeVariantScores(aScore, vScore, variantName='variant', *, inPlace=False): for returnPart, vPart in zip(returnObj.parts, vScore.parts): mergeVariantMeasureStreams(returnPart, vPart, variantName, inPlace=True) - if inPlace is False: + if not inPlace: return returnObj @@ -933,7 +933,7 @@ def mergeVariantMeasureStreams(streamX, streamY, variantName='variant', *, inPla >>> parisStream[variant.Variant][2].replacementQuarterLength 8.0 ''' - if inPlace is True: + if inPlace: returnObj = streamX else: returnObj = streamX.coreCopyAsDerivation('mergeVariantMeasureStreams') @@ -972,7 +972,7 @@ def mergeVariantMeasureStreams(streamX, streamY, variantName='variant', *, inPla addVariant(returnObj, startOffset, yRegion, variantName=variantName, replacementQuarterLength=replacementQuarterLength) - if inPlace is True: + if inPlace: return else: return returnObj @@ -1182,7 +1182,7 @@ def mergeVariantsEqualDuration(streams, variantNames, *, inPlace=False): which are of different lengths ''' - if inPlace is True: + if inPlace: returnObj = streams[0] else: returnObj = streams[0].coreCopyAsDerivation('mergeVariantsEqualDuration') @@ -1333,7 +1333,7 @@ def mergePartAsOssia(mainPart, ossiaPart, ossiaName, ... ''' - if inPlace is True: + if inPlace: returnObj = mainPart else: returnObj = mainPart.coreCopyAsDerivation('mergePartAsOssia') @@ -1376,7 +1376,7 @@ def mergePartAsOssia(mainPart, ossiaPart, ossiaName, variantName=ossiaName, variantGroups=None, replacementQuarterLength=None) - if inPlace is True: + if inPlace: return else: return returnObj @@ -1598,7 +1598,7 @@ def refineVariant(s, sVariant, *, inPlace=False): if sVariant not in s.getElementsByClass(Variant): raise VariantException(f'{sVariant} not found in stream {s}.') - if inPlace is True: + if inPlace: returnObject = s variantRegion = sVariant else: @@ -1689,7 +1689,7 @@ def _mergeVariantMeasureStreamsCarefully(streamX, streamY, variantName, *, inPla ''' # stream that will be returned - if inPlace is True: + if inPlace: returnObject = streamX variantObject = streamY else: @@ -2057,7 +2057,7 @@ def _mergeVariants(streamA, streamB, *, variantName=None, inPlace=False): '_mergeVariants cannot merge streams which are of different lengths' ) - if inPlace is True: + if inPlace: returnObj = streamA else: returnObj = copy.deepcopy(streamA) @@ -2138,7 +2138,7 @@ def _mergeVariants(streamA, streamB, *, variantName=None, inPlace=False): inVariant = False noteBuffer = [] - if inPlace is True: + if inPlace: return None else: return returnObj @@ -2237,7 +2237,7 @@ def makeAllVariantsReplacements(streamWithVariants, ''' - if inPlace is True: + if inPlace: returnStream = streamWithVariants else: returnStream = copy.deepcopy(streamWithVariants) @@ -2249,7 +2249,7 @@ def makeAllVariantsReplacements(streamWithVariants, _doVariantFixingOnStream(returnStream, variantNames=variantNames) - if inPlace is True: + if inPlace: return else: return returnStream From 97d9ba6fb9d1adc3d6ddc8e5c84e8d528ccea67a Mon Sep 17 00:00:00 2001 From: Michael Scott Asato Cuthbert Date: Fri, 21 Aug 2026 14:35:27 -1000 Subject: [PATCH 2/2] Fix two inverted conditions from the bool simplification `x is not True` and `x is not False` are negations; fcdb678 rewrote both as bare truthiness tests, flipping their sense. m21ToXml.noteToXml: `d.isGrace is not True` became `d.isGrace`, so was written only for grace notes -- where MusicXML forbids it -- and omitted from every ordinary note. All MusicXML output was invalid. recording.samplesFromRecording: `storeFile is not False` became `not storeFile`, so the wave file was written only when the caller asked for no file, and the `isinstance(storeFile, str)` filename branch became unreachable. Annotation widened to bool|str to match that branch; the function is `# pragma: no cover`, so nothing caught this. AI-assisted (Claude) --- music21/audioSearch/recording.py | 4 ++-- music21/musicxml/m21ToXml.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/music21/audioSearch/recording.py b/music21/audioSearch/recording.py index c390bd32bf..c934d22513 100644 --- a/music21/audioSearch/recording.py +++ b/music21/audioSearch/recording.py @@ -39,7 +39,7 @@ def samplesFromRecording(seconds=10.0, - storeFile: bool = True, + storeFile: bool|str = True, recordFormat=None, recordChannels=default_recordChannels, recordSampleRate=default_recordSampleRate, @@ -78,7 +78,7 @@ def samplesFromRecording(seconds=10.0, st.close() p_audio.terminate() - if not storeFile: + if storeFile: if isinstance(storeFile, str): waveFilename = storeFile else: diff --git a/music21/musicxml/m21ToXml.py b/music21/musicxml/m21ToXml.py index 24ef075cf6..034c215571 100644 --- a/music21/musicxml/m21ToXml.py +++ b/music21/musicxml/m21ToXml.py @@ -4106,7 +4106,7 @@ def noteToXml(self, n: note.GeneralNote, noteIndexInChord=0, chordParent=None): elif n.isRest: SubElement(mxNote, 'rest') - if d.isGrace: + if not d.isGrace: mxDuration = self.durationXml(d) mxNote.append(mxDuration) # divisions only