Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions music21/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2805,9 +2805,8 @@ def duration(self, durationObj: Duration):
try:
durationObj.client = self
except TypeError:
# durationObj is an immutable FrozenDuration (e.g. one from a
# TimeSignature): it never changes, so it needs no client
# back-reference and can be held shared as-is.
# a FrozenDuration (e.g. from a TimeSignature) never changes,
# so it has nothing to tell a client
if not isinstance(durationObj, FrozenDuration):
raise
if durationObjAlreadyExists:
Expand Down
2 changes: 1 addition & 1 deletion music21/common/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ class EqualSlottedObjectMixin(SlottedObjectMixin):

def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
# Defer to the other operand rather than declaring inequality
# let the other object's __eq__ decide
return NotImplemented
for thisSlot in self._getSlotsRecursive():
if thisSlot == 'id':
Expand Down
36 changes: 14 additions & 22 deletions music21/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -1722,8 +1722,7 @@ def __eq__(self, other):
>>> tupDur1 == tupDur2
True

Grace durations are conceptually distinct, so they never equal an ordinary
Duration:
A grace duration never equals an ordinary Duration:

>>> graceDur1 = tupDur1.getGraceDuration()
>>> graceDur1 == tupDur1
Expand All @@ -1735,10 +1734,9 @@ def __eq__(self, other):
>>> graceDur1 == graceDur2
True

A :class:`FrozenDuration` differs from a Duration only in being immutable,
so it compares equal to an otherwise-identical Duration:
A :class:`FrozenDuration` equals a Duration of the same value:

>>> duration.Duration(2.0) == duration.FrozenDuration(quarterLength=2.0)
>>> duration.FrozenDuration('half') == duration.Duration('half')
True

Link status must be the same:
Expand Down Expand Up @@ -1780,8 +1778,7 @@ def __eq__(self, other):
'''
if not isinstance(other, Duration):
return False
# A grace duration is conceptually a different thing from an ordinary
# duration, even at the same length; a FrozenDuration is not.
# grace durations only equal other grace durations
if self.isGrace != other.isGrace:
return False

Expand Down Expand Up @@ -3156,8 +3153,7 @@ def __copy__(self):

def unfreeze(self) -> Duration:
'''
Return an independent, mutable :class:`Duration` with the same value --
faithfully preserving components, tuplets, etc.
Return a :class:`Duration` with the same value that can be changed.

>>> fd = duration.FrozenDuration(type='half', dots=1)
>>> d = fd.unfreeze()
Expand All @@ -3166,15 +3162,15 @@ def unfreeze(self) -> Duration:
>>> type(d) is duration.Duration
True

The copy is mutable and fully independent of the original:
Changing it leaves the original alone:

>>> d.dots = 0
>>> d.quarterLength
2.0
>>> fd.dots
1

Tuplets and unlinked status survive the round trip:
Tuplets come along too, as copies:

>>> fd2 = duration.FrozenDuration(2/3)
>>> d2 = fd2.unfreeze()
Expand All @@ -3187,11 +3183,8 @@ def unfreeze(self) -> Duration:

AI-assisted (Claude).
'''
# Copy the frozen state straight onto a bare mutable Duration. __new__
# skips __init__ (which would just set defaults __setstate__ overwrites);
# __setstate__ then restores every slot. Components/quarterLength/link
# status are immutable and shared; only tuplets are mutable, so deep-copy
# those (when any) -- meter durations have none, so it is skipped entirely.
# Skips __init__, since __setstate__ overwrites everything it sets. Tuplets
# are the only part that can change, so they alone need copying.
new = Duration.__new__(Duration)
new.__setstate__(self.__getstate__())
if self._tuplets:
Expand All @@ -3201,8 +3194,8 @@ def unfreeze(self) -> Duration:

def augmentOrDiminish(self, amountToScale: OffsetQLIn, retainComponents=False) -> Duration:
'''
Like :meth:`Duration.augmentOrDiminish`, but always returns a new, mutable
Duration.
Like :meth:`Duration.augmentOrDiminish`, but always returns an ordinary
Duration, which can be changed.

>>> fd = duration.FrozenDuration(quarterLength=1.0)
>>> d = fd.augmentOrDiminish(0.5)
Expand All @@ -3217,7 +3210,7 @@ def augmentOrDiminish(self, amountToScale: OffsetQLIn, retainComponents=False) -
def splitDotGroups(self, *, inPlace=False) -> Duration:
'''
Like :meth:`Duration.splitDotGroups`, but `inPlace` must be False since a
FrozenDuration cannot be mutated.
FrozenDuration cannot be changed.

>>> fd = duration.FrozenDuration(quarterLength=1.0)
>>> fd.splitDotGroups()
Expand Down Expand Up @@ -3810,8 +3803,7 @@ def testFrozenDurationEquality(self):
self.assertFalse(d != fd)
self.assertFalse(fd != d)

# Equal even from different construction paths (differing internal flags
# that a slot-by-slot comparison would trip on).
# Equal however they were made, though their internal flags differ.
self.assertEqual(Duration(type='half'), fd)
self.assertEqual(fd, Duration(type='half'))

Expand All @@ -3820,7 +3812,7 @@ def testFrozenDurationEquality(self):
self.assertNotEqual(fd, Duration(1.0))
self.assertNotEqual(Duration(1.0), fd)

# A grace duration is conceptually distinct, in either order.
# A grace duration never equals an ordinary one, in either order.
grace = d.getGraceDuration()
self.assertNotEqual(grace, d)
self.assertNotEqual(d, grace)
Expand Down
35 changes: 14 additions & 21 deletions music21/meter/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Authors: Christopher Ariza
# Michael Scott Asato Cuthbert
#
# Copyright: Copyright © 2009-2024 Michael Scott Asato Cuthbert
# Copyright: Copyright © 2009-2026 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# -----------------------------------------------------------------------------
'''
Expand Down Expand Up @@ -40,12 +40,9 @@

environLocal = environment.Environment('meter')

# Cache of the fully-configured MeterSequences a TimeSignature.load() produces for a
# given (value, divisions). Each value is a 4-tuple in the fixed order
# (displaySequence, beamSequence, beatSequence, accentSequence). The sequences are
# immutable and shared, and any later change to a TimeSignature is copy-on-write, so
# repeated TimeSignatures of the same meter can reuse them and skip the (hashing-heavy)
# rebuild entirely.
# The sequences TimeSignature.load() made for each (value, divisions), in the order
# (displaySequence, beamSequence, beatSequence, accentSequence). Sequences cannot
# change, so every later TimeSignature('4/4') can use the same ones and skip building them.
_defaultSequenceCache: dict[
tuple[str, t.Any],
tuple[MeterSequence, MeterSequence, MeterSequence, MeterSequence],
Expand Down Expand Up @@ -608,16 +605,16 @@ def load(self, value: str, divisions=None):
value = '2/2'
self.symbol = 'cut'

# divisions may be list-like -- e.g. ['2/8', '3/8'] (Ariza & Cuthbert 2010) --
# so normalize a list to a tuple to make it a usable cache key.
# divisions may be a list, like ['2/8', '3/8'] (Ariza & Cuthbert 2010),
# but a dictionary key needs a tuple.
keyDivisions = tuple(divisions) if isinstance(divisions, list) else divisions
cacheKey = (value, keyDivisions)
cached = None
cacheable = True
try:
cached = _defaultSequenceCache.get(cacheKey)
except TypeError:
cacheable = False # still unhashable (rare): skip the cache
cacheable = False # rare: cannot be a dictionary key, so skip the cache
if cached is not None:
(self.displaySequence, self.beamSequence,
self.beatSequence, self.accentSequence) = cached
Expand Down Expand Up @@ -812,9 +809,8 @@ def barDuration(self) -> duration.Duration:
>>> meter.TimeSignature().barDuration
<music21.duration.Duration 4.0>

Note: this currently returns an ordinary (mutable) Duration, but it is
expected to return an immutable :class:`~music21.duration.FrozenDuration`
in v12 -- do not rely on being able to modify it in place.
Avoid changing the Duration you get here: in v12 it is expected to become a
:class:`~music21.duration.FrozenDuration`, which cannot be changed.
'''
if self._overriddenBarDuration:
return self._overriddenBarDuration
Expand All @@ -823,8 +819,7 @@ def barDuration(self) -> duration.Duration:
if beamSequence is not None:
# could come from self.beamSequence, self.accentSequence,
# self.displaySequence, self.accentSequence
# unfreeze() so callers get an ordinary, mutable Duration; the meter's
# own duration stays a shared, immutable FrozenDuration internally.
# unfreeze() to allow mutability till v12
return beamSequence.duration.unfreeze()

# should never happen.
Expand Down Expand Up @@ -1342,8 +1337,8 @@ def _setDefaultAccentWeights(self, depth: int = 3) -> None:
# set weights on accent partitions
self.accentSequence = self.accentSequence.partitioned([1] * accentCount)
for i in range(accentCount):
# get values from weightValues dictionary; terminals are
# immutable, so replace each with a re-weighted cached one
# get values from weightValues dictionary; terminals cannot
# change, so replace each with one of the new weight
mt = self.accentSequence[i]
self.accentSequence = self.accentSequence.setIndex(
i, getMeterTerminal(
Expand Down Expand Up @@ -1668,7 +1663,7 @@ def getAccent(self, qLenPos: OffsetQL) -> bool:
>>> a.getAccent(2.0)
True
'''
pos = 0
pos: OffsetQL = 0.0
qLenPos = opFrac(qLenPos)
for i in range(len(self.accentSequence)):
if pos == qLenPos:
Expand Down Expand Up @@ -2128,9 +2123,7 @@ def getBeatDepth(self, qLenPos, align='quantize'):
>>> b = meter.TimeSignature('3/4', 1)
>>> b.beatSequence = b.beatSequence.setIndex(0, b.beatSequence[0].subdivide(3))

Subdivide every component of ``beatSequence[0]`` by 2. Since the sequences
are immutable, build up the new inner sequence in a variable and then set it
back into ``beatSequence`` once:
Divide each part of ``beatSequence[0]`` in two, then put the result back:

>>> inner = b.beatSequence[0]
>>> for i in range(len(inner)):
Expand Down
Loading
Loading