-
Notifications
You must be signed in to change notification settings - Fork 395
/
base.py
4212 lines (3471 loc) · 155 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
863
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Name: base.py
# Purpose: Music21 base classes and important utilities
#
# Authors: Michael Scott Asato Cuthbert
# Christopher Ariza
#
# Copyright: Copyright © 2006-2023 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# -----------------------------------------------------------------------------
'''
`music21.base` is what you get in `music21` if you type ``import music21``. It
contains all the most low-level objects that also appear in the music21 module
(i.e., music21.base.Music21Object is the same as music21.Music21Object).
Music21 base classes for :class:`~music21.stream.Stream` objects and all
elements contained within them including Notes, etc. Additional objects for
defining and manipulating elements are included.
The namespace of this file, as all base.py files, is loaded into the package
that contains this file via __init__.py. Everything in this file is thus
available after importing `music21`.
>>> import music21
>>> music21.Music21Object
<class 'music21.base.Music21Object'>
>>> music21.VERSION_STR
'9.0.0a12'
Alternatively, after doing a complete import, these classes are available
under the module "base":
>>> base.Music21Object
<class 'music21.base.Music21Object'>
'''
from __future__ import annotations
import builtins
from collections.abc import Generator, Iterable
import copy
import functools
from importlib.util import find_spec
import typing as t
from typing import overload # Pycharm can't do alias
import unittest
import warnings
import weakref
from music21._version import __version__, __version_info__
from music21 import common
from music21.common.enums import ElementSearch, OffsetSpecial
from music21.common.numberTools import opFrac
from music21.common.types import OffsetQL, OffsetQLIn
from music21 import defaults
from music21.derivation import Derivation
from music21.duration import Duration, DurationException
from music21.editorial import Editorial # import class directly to not conflict with property.
from music21 import environment
from music21 import exceptions21
from music21 import prebase
from music21.sites import Sites, SitesException, WEAKREF_ACTIVE
from music21.style import Style # pylint: disable=unused-import
from music21.sorting import SortTuple, ZeroSortTupleLow, ZeroSortTupleHigh
# needed for temporal manipulations; not music21 objects
from music21 import tie
if t.TYPE_CHECKING:
import fractions
from io import IOBase
import pathlib
from music21 import meter
from music21 import stream
from music21 import spanner
_M21T = t.TypeVar('_M21T', bound='music21.base.Music21Object')
# all other music21 modules below...
# -----------------------------------------------------------------------------
# version string and tuple must be the same
VERSION = __version_info__
VERSION_STR = __version__
# -----------------------------------------------------------------------------
__all__ = [
'Music21Exception',
'SitesException',
'Music21ObjectException',
'ElementException',
'Groups',
'Music21Object',
'ElementWrapper',
'VERSION',
'VERSION_STR',
]
# N.B. for PyDev "all" import working, we need to list this
# separately in "music21/__init__.py"
# so make sure to update in both places
# ----all exceptions are in the exceptions21 package.
Music21Exception = exceptions21.Music21Exception
environLocal = environment.Environment('base')
_missingImport = []
for modName in ('matplotlib', 'numpy'):
loader = find_spec(modName)
if loader is None: # pragma: no cover
_missingImport.append(modName)
del find_spec
del modName
if _missingImport: # pragma: no cover
if environLocal['warnings'] in (1, '1', True):
environLocal.warn(common.getMissingImportStr(_missingImport),
header='music21:')
class Music21ObjectException(exceptions21.Music21Exception):
pass
class ElementException(exceptions21.Music21Exception):
pass
# -----------------------------------------------------------------------------
# for contextSites searches...
class ContextTuple(t.NamedTuple):
site: stream.Stream
offset: OffsetQL
recurseType: stream.enums.RecursionType
class ContextSortTuple(t.NamedTuple):
site: stream.Stream
offset: SortTuple
recurseType: stream.enums.RecursionType
# pseudo class for returning splitAtX() type commands.
class _SplitTuple(tuple):
'''
>>> st = base._SplitTuple([1, 2])
>>> st.spannerList = [3]
>>> st
(1, 2)
>>> st.spannerList
[3]
>>> a, b = st
>>> a
1
>>> b
2
>>> st.__class__
<class 'music21.base._SplitTuple'>
'''
def __new__(cls, tupEls):
# noinspection PyTypeChecker
return super(_SplitTuple, cls).__new__(cls, tuple(tupEls))
def __init__(self, tupEls): # pylint: disable=super-init-not-called
self.spannerList = []
# -----------------------------------------------------------------------------
# make subclass of set once that is defined properly
class Groups(list): # no need to inherit from slotted object
'''
Groups is a list (subclass) of strings used to identify
associations that an element might have.
(in the future, Groups will become a set subclass)
The Groups object enforces that all elements must be strings, and that
the same element cannot be provided more than once.
NOTE: In the future, spaces will not be allowed in group names.
>>> g = Groups()
>>> g.append('hello')
>>> g[0]
'hello'
>>> g.append('hello') # not added as already present
>>> len(g)
1
>>> g
['hello']
>>> g.append(5) # type: ignore
Traceback (most recent call last):
music21.exceptions21.GroupException: Only strings can be used as group names, not 5
'''
# could be made into a set instance, but actually
# timing: a subclassed list and a set are almost the same speed
# and set does not allow calling by number
# this speeds up creation slightly...
__slots__ = ()
def _validName(self, value: str):
if not isinstance(value, str):
raise exceptions21.GroupException('Only strings can be used as group names, '
f'not {value!r}')
# if ' ' in value:
# raise exceptions21.GroupException('Spaces are not allowed as group names')
def append(self, value: str) -> None:
self._validName(value)
if not list.__contains__(self, value):
list.append(self, value)
def __setitem__(self, i, y):
self._validName(y)
super().__setitem__(i, y)
def __eq__(self, other: object):
'''
Test Group equality. In normal lists, order matters; here it does not. More like a set.
>>> a = base.Groups()
>>> a.append('red')
>>> a.append('green')
>>> a
['red', 'green']
>>> b = base.Groups()
>>> b.append('green')
>>> a == b
False
>>> b.append('reD') # case insensitive
>>> a == b
True
>>> a == ['red', 'green'] # need both to be groups
False
>>> c = base.Groups()
>>> c.append('black')
>>> c.append('tuba')
>>> a == c
False
'''
if not isinstance(other, Groups):
return False
if len(self) != len(other):
return False
sls = sorted(self)
slo = sorted(other)
for x in range(len(sls)):
if sls[x].lower() != slo[x].lower():
return False
return True
# -----------------------------------------------------------------------------
_EQUALITY_SENTINEL_SELF = object()
_EQUALITY_SENTINEL_OTHER = object()
@functools.cache
def _getEqualityAttributes(cls) -> frozenset[str]:
'''
Get equality attributes for a class. Cached.
>>> base._getEqualityAttributes(base.Music21Object)
frozenset({'duration'})
>>> 'location' in base._getEqualityAttributes(bar.Barline)
True
>>> 'pitch' in base._getEqualityAttributes(bar.Barline)
False
'''
equalityAttributes = set()
# equalityAttributesIgnore works, but not yet needed.
# equalityAttributesIgnore = set()
# for klass in [cls, *cls.mro()]:
# if hasattr(klass, 'equalityAttributesIgnore'):
# ka = klass.equalityAttributesIgnore
# if isinstance(ka, str): # mistake. Happens TOO often:
# ka = (ka,)
# equalityAttributesIgnore |= set(ka)
for klass in [cls, *cls.mro()]:
if hasattr(klass, 'equalityAttributes'):
ka = klass.equalityAttributes
if isinstance(ka, str): # mistake. Happens TOO often:
ka = (ka,)
equalityAttributes |= set(ka)
# equalityAttributes.difference_update(equalityAttributesIgnore)
return frozenset(equalityAttributes)
class Music21Object(prebase.ProtoM21Object):
'''
Music21Object is the base class for all elements that can go into Streams.
Notes, Clefs, TimeSignatures are all sublcasses of Music21Object. Durations
and Pitches (which need to be attached to Notes, etc.) are not.
All music21 objects have these pieces of information:
1. id: identification string unique to the object's container (optional).
Defaults to the `id()` of the element.
2. groups: a :class:`~music21.base.Groups` object: which is a
list of strings identifying internal sub-collections
(voices, parts, selections) to which this element belongs
3. duration: :class:`~music21.duration.Duration` object representing the length of the object
4. activeSite: a reference to the currently active :class:`~music21.stream.Stream` or None
5. offset: a floating point or Fraction value, generally in quarter lengths,
specifying the position of the object in a site.
6. priority: int representing the position of an object among all
objects at the same offset.
7. sites: a :class:`~music21.base.Sites` object that stores all
the Streams and Contexts that an
object is in.
8. derivation: a :class:`~music21.derivation.Derivation` object, or None, that shows
where the object came from.
9. style: a :class:`~music21.style.Style` object, that contains Style information
automatically created if it doesn't exist, so check `.hasStyleInformation` first
if that is not desired.
10. editorial: a :class:`~music21.editorial.Editorial` object
Each of these may be passed in as a named keyword to any music21 object.
Some of these may be intercepted by the subclassing object (e.g., duration
within Note)
**Equality**
For historical reasons, music21 uses a different idea of object equality
for Music21Objects than recommended by modern Python standards.
Two Music21Objects are equal if they are the same class and same duration.
Their offset, activeSite, id, and groups do not matter for equality.
Since these two objects are therefore not interchangable, they do not have
the same hash value.
>>> obj1 = base.Music21Object(id='obj1')
>>> obj2 = base.Music21Object(id='obj2')
>>> obj1 == obj2
True
>>> hash(obj1) == hash(obj2)
False
This has the stange side effect that structures that use equality to
report containment (such as lists and tuples) will report differently from
structures that use hash values to report containment (such as dicts and sets):
>>> obj1 in [obj2]
True
>>> obj1 in {obj2}
False
Subclasses need to apply stricter criteria for equality, like Barline does here
with `.location`
>>> bar1 = bar.Barline('double', 'left')
>>> bar2 = bar.Barline('double', 'right')
>>> bar1 == bar2
False
>>> bar2.location = 'left'
>>> bar1 == bar2
True
>>> bar1.duration.type = 'whole' # Buh?
>>> bar1 == bar2
False
In general, a subclass of Music21Object must match all super-class criteria for
equality before they can be considered equal themselves. However, there are some
exceptions. For instance, RomanNumeral objects with the same figure and key are
equal even if their notes are in different octaves or have different doublings.
Developers creating their own Music21Object subclasses should add a class attribute
`equalityAttributes = ('one', 'two')`. (Remember that as a tuple of strings, if there
is only one string, don't forget the trailing comma: `('only',)`.
>>> class CarolineShawBreathMark(base.Music21Object):
... equalityAttributes = ('direction',)
... def __init__(self, direction, speed):
... super().__init__(self)
... self.direction = direction
... self.speed = speed
>>> bm1 = CarolineShawBreathMark('in', 'fast')
>>> bm2 = CarolineShawBreathMark('out', 'fast')
>>> bm1 == bm2
False
"speed" is not in the equalityAttributes so it can differ while objects are still
equal.
>>> bm3 = CarolineShawBreathMark('in', 'slow')
>>> bm1 == bm3
True
'''
classSortOrder: int | float = 20 # default classSortOrder
# these values permit fast class comparisons for performance critical cases
isStream = False
_styleClass: type[Style] = Style
equalityAttributes: tuple[str, ...] = ('duration',)
# equalityAttributesIgnore: tuple[str, ...] = () # this must be defined anew in each subclass.
# define order for presenting names in documentation; use strings
_DOC_ORDER: list[str] = []
# documentation for all attributes (not properties or methods)
_DOC_ATTR: dict[str, str] = {
'groups': '''An instance of a :class:`~music21.base.Groups`
object which describes
arbitrary `Groups` that this object belongs to.''',
'sites': '''a :class:`~music21.sites.Sites` object that stores
references to Streams that hold this object.''',
'isStream': '''Boolean value for quickly identifying
:class:`~music21.stream.Stream` objects (False by default).''',
'classSortOrder': '''Property which returns an number (int or otherwise)
depending on the class of the Music21Object that
represents a priority for an object based on its class alone --
used as a tie for stream sorting in case two objects have the
same offset and priority. Lower numbers are sorted to the left
of higher numbers. For instance, Clef, KeySignature, TimeSignature
all come (in that order) before Note.
All undefined classes have classSortOrder of 20 -- same as note.Note
>>> m21o = base.Music21Object()
>>> m21o.classSortOrder
20
>>> tc = clef.TrebleClef()
>>> tc.classSortOrder
0
>>> ks = key.KeySignature(3)
>>> ks.classSortOrder
2
New classes can define their own default classSortOrder
>>> class ExampleClass(base.Music21Object):
... classSortOrder = 5
...
>>> ec1 = ExampleClass()
>>> ec1.classSortOrder
5
''',
}
def __init__(self,
id: str | int | None = None, # pylint: disable=redefined-builtin
groups: Groups | None = None,
sites: Sites | None = None,
duration: Duration | None = None,
activeSite: stream.Stream | None = None,
style: Style | None = None,
editorial: Editorial | None = None,
offset: OffsetQL = 0.0,
quarterLength: OffsetQLIn | None = None,
**keywords):
# do not call super().__init__() since it just wastes time
self._id: str | int | None = id
# None is stored as the internal location of an obj w/o any sites
self._activeSite: stream.Stream | weakref.ReferenceType | None = None
# offset when no activeSite is available
self._naiveOffset: OffsetQL = offset
# offset when activeSite is already garbage collected/dead,
# as in short-lived sites
# like .getElementsByClass().stream()
self._activeSiteStoredOffset: float | fractions.Fraction | None = None
# store a derivation object to track derivations from other Streams
# pass a reference to this object
self._derivation: Derivation | None = None
self._style: Style | None = style
self._editorial: Editorial | None = None
# private duration storage; managed by property
self._duration: Duration | None = duration
if duration is not None:
duration.client = self
self._priority = 0 # default is zero
# store cached values here:
self._cache: dict[str, t.Any] = {}
self.groups = groups or Groups()
self.sites = sites or Sites()
# a duration object is not created until the .duration property is
# accessed with _getDuration(); this is a performance optimization
if activeSite is not None:
self.activeSite = activeSite
if quarterLength is not None:
self.duration.quarterLength = quarterLength
def __eq__(self: _M21T, other) -> t.TypeGuard[_M21T]:
'''
Define equality for Music21Objects. See main class docs.
'''
cls = t.cast(type, self.__class__)
if not isinstance(other, cls):
return False
for attr in _getEqualityAttributes(cls):
if (getattr(self, attr, _EQUALITY_SENTINEL_SELF)
!= getattr(other, attr, _EQUALITY_SENTINEL_OTHER)):
return False
return True
def __hash__(self) -> int:
'''
Restore hashing, but only on id(self)
'''
return id(self) >> 4
@property
def id(self) -> int | str:
'''
A unique identification string or int; not to be confused with Python's
built-in `id()` method. However, if not set, will return
Python's `id()` number.
"Unique" is intended with respect to the stream hierarchy one is likely
to query with :meth:`~music21.stream.Stream.getElementById`. For
instance, the `.id` of a Voice should be unique in any single Measure,
but the id's may reset from measure to measure across a Part.
'''
if self._id is not None:
return self._id
return builtins.id(self)
@id.setter
def id(self, new_id: int | str):
if isinstance(new_id, int) and new_id > defaults.minIdNumberToConsiderMemoryLocation:
msg = 'Setting an ID that could be mistaken for a memory location '
msg = f'is discouraged: got {new_id}'
warnings.warn(msg)
self._id = new_id
def mergeAttributes(self, other: Music21Object) -> None:
'''
Merge all elementary, static attributes. Namely,
`id` and `groups` attributes from another music21 object.
Can be useful for copy-like operations.
>>> m1 = base.Music21Object()
>>> m2 = base.Music21Object()
>>> m1.id = 'music21Object1'
>>> m1.groups.append('group1')
>>> m2.mergeAttributes(m1)
>>> m2.id
'music21Object1'
>>> 'group1' in m2.groups
True
'''
if other.id != id(other):
self.id = other.id
self.groups = copy.deepcopy(other.groups)
def _deepcopySubclassable(self: _M21T,
memo: dict[int, t.Any] | None = None,
*,
ignoreAttributes: set[str] | None = None) -> _M21T:
'''
Subclassable __deepcopy__ helper so that the same attributes
do not need to be called for each Music21Object subclass.
ignoreAttributes is a set of attributes not to copy via
the default deepcopy style. More can be passed to it. But calling
functions are responsible
* Changed in v9: removeFromIgnore removed;
never used and this is performance critical.
'''
defaultIgnoreSet = {'_derivation', '_activeSite', '_sites', '_cache'}
if not self.groups:
defaultIgnoreSet.add('groups')
# duration is smart enough to do itself.
# sites is smart enough to do itself
if ignoreAttributes is None:
ignoreAttributes = defaultIgnoreSet
else:
ignoreAttributes = ignoreAttributes | defaultIgnoreSet
new = common.defaultDeepcopy(self, memo, ignoreAttributes=ignoreAttributes)
setattr(new, '_cache', {})
setattr(new, '_sites', Sites())
if 'groups' in defaultIgnoreSet:
new.groups = Groups()
# was: keep the old ancestor but need to update the client
# 2.1 : NO, add a derivation of __deepcopy__ to the client
newDerivation = Derivation(client=new)
newDerivation.origin = self
newDerivation.method = '__deepcopy__'
setattr(new, '_derivation', newDerivation)
# None activeSite is correct for new value
# must do this after copying
new.purgeOrphans()
return new
def __deepcopy__(self: _M21T, memo: dict[int, t.Any] | None = None) -> _M21T:
'''
Helper method to copy.py's deepcopy function. Call it from there.
memo=None is the default as specified in copy.py
Problem: if an attribute is defined with an underscore (_priority) but
is also made available through a property (e.g. priority) using dir(self)
results in the copy happening twice. Thus, __dict__.keys() is used.
>>> from copy import deepcopy
>>> n = note.Note('A')
>>> n.offset = 1.0
>>> n.groups.append('flute')
>>> n.groups
['flute']
>>> idN = n.id
>>> idN > 10000 # pointer
True
>>> b = deepcopy(n)
>>> b.offset = 2.0
>>> n is b
False
>>> b.id != n.id
True
>>> n.pitch.accidental = '-'
>>> b.name
'A'
>>> n.offset
1.0
>>> b.offset
2.0
>>> n.groups[0] = 'bassoon'
>>> ('flute' in n.groups, 'flute' in b.groups)
(False, True)
'''
return self._deepcopySubclassable(memo)
def __getstate__(self) -> dict[str, t.Any]:
state = self.__dict__.copy()
state['_derivation'] = None
state['_activeSite'] = None
return state
def __setstate__(self, state: dict[str, t.Any]):
# defining self.__dict__ upon initialization currently breaks everything
object.__setattr__(self, '__dict__', state) # pylint: disable=attribute-defined-outside-init
def _reprInternal(self) -> str:
'''
If `x.id` is not the same as `id(x)`, then that id is used instead:
>>> b = base.Music21Object()
>>> b._reprInternal()
'object at 0x129a903b1'
>>> b.id = 'hi'
>>> b._reprInternal()
'id=hi'
'''
# hasattr is here because of Metadata.__getattr__()
if not hasattr(self, 'id') or self.id == id(self):
return super()._reprInternal()
reprId = self.id
try:
reprId = hex(int(reprId))
except (ValueError, TypeError):
pass
return f'id={reprId}'
# --------------------------------------------------------------------------
@property
def hasEditorialInformation(self) -> bool:
'''
Returns True if there is a :class:`~music21.editorial.Editorial` object
already associated with this object, False otherwise.
Calling .editorial on an object will always create a new
Editorial object, so even though a new Editorial object isn't too expensive
to create, this property helps to prevent creating new Editorial objects
more than is necessary.
>>> mObj = base.Music21Object()
>>> mObj.hasEditorialInformation
False
>>> mObj.editorial
<music21.editorial.Editorial {}>
>>> mObj.hasEditorialInformation
True
'''
# anytime something is changed here, change in style.StyleMixin and vice-versa
return not (self._editorial is None)
@property
def editorial(self) -> Editorial:
'''
a :class:`~music21.editorial.Editorial` object that stores editorial information
(comments, footnotes, harmonic information, ficta).
Created automatically as needed:
>>> n = note.Note('C4')
>>> n.editorial
<music21.editorial.Editorial {}>
>>> n.editorial.ficta = pitch.Accidental('sharp')
>>> n.editorial.ficta
<music21.pitch.Accidental sharp>
>>> n.editorial
<music21.editorial.Editorial {'ficta': <music21.pitch.Accidental sharp>}>
'''
# Dev note: because the property "editorial" shadows module editorial,
# typing has to be in quotes.
# anytime something is changed here, change in style.StyleMixin and vice-versa
if self._editorial is None:
self._editorial = Editorial()
return self._editorial
@editorial.setter
def editorial(self, ed: Editorial):
self._editorial = ed
@property
def hasStyleInformation(self) -> bool:
'''
Returns True if there is a :class:`~music21.style.Style` object
already associated with this object, False otherwise.
Calling .style on an object will always create a new
Style object, so even though a new Style object isn't too expensive
to create, this property helps to prevent creating new Styles more than
necessary.
>>> mObj = base.Music21Object()
>>> mObj.hasStyleInformation
False
>>> mObj.style
<music21.style.Style object at 0x10b0a2080>
>>> mObj.hasStyleInformation
True
'''
# anytime something is changed here, change in style.StyleMixin and vice-versa
return not (self._style is None)
@property
def style(self) -> Style:
'''
Returns (or Creates and then Returns) the Style object
associated with this object, or sets a new
style object. Different classes might use
different Style objects because they might have different
style needs (such as text formatting or bezier positioning)
Eventually will also query the groups to see if they have
any styles associated with them.
>>> n = note.Note()
>>> st = n.style
>>> st
<music21.style.NoteStyle object at 0x10ba96208>
>>> st.absoluteX = 20.0
>>> st.absoluteX
20.0
>>> n.style = style.Style()
>>> n.style.absoluteX is None
True
'''
# anytime something is changed here, change in style.StyleMixin and vice-versa
if not self.hasStyleInformation:
StyleClass = self._styleClass
self._style = StyleClass()
assert self._style is not None # for mypy.
return self._style
@style.setter
def style(self, newStyle: Style | None):
self._style = newStyle
# convenience.
@property
def quarterLength(self) -> OffsetQL:
'''
Set or Return the Duration as represented in Quarter Length, possibly as a fraction.
Same as setting `.duration.quarterLength`.
>>> n = note.Note()
>>> n.quarterLength = 2.0
>>> n.quarterLength
2.0
>>> n.quarterLength = 1/3
>>> n.quarterLength
Fraction(1, 3)
'''
return self.duration.quarterLength
@quarterLength.setter
def quarterLength(self, value: OffsetQLIn):
self.duration.quarterLength = value
@property
def derivation(self) -> Derivation:
'''
Return the :class:`~music21.derivation.Derivation` object for this element.
Or create one if none exists:
>>> n = note.Note()
>>> n.derivation
<Derivation of <music21.note.Note C> from None>
>>> import copy
>>> n2 = copy.deepcopy(n)
>>> n2.pitch.step = 'D' # for seeing easier...
>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via '__deepcopy__'>
>>> n2.derivation.origin is n
True
Note that (for now at least) derivation.origin is NOT a weakref:
>>> del n
>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via '__deepcopy__'>
>>> n2.derivation.origin
<music21.note.Note C>
'''
if self._derivation is None:
self._derivation = Derivation(client=self)
return self._derivation
@derivation.setter
def derivation(self, newDerivation: Derivation | None) -> None:
self._derivation = newDerivation
def clearCache(self, **keywords) -> None:
'''
A number of music21 attributes (especially with Chords and RomanNumerals, etc.)
are expensive to compute and are therefore cached. Generally speaking
objects are responsible for making sure that their own caches are up to date,
but a power user might want to do something in an unusual way (such as manipulating
private attributes on a Pitch object) and need to be able to clear caches.
That's what this is here for. If all goes well, you'll never need to call it
unless you're expanding music21's core functionality.
`**keywords` is not used in Music21Object but is included for subclassing.
Look at :func:`~music21.common.decorators.cacheMethod` for the other half of this
utility.
* New in v6: exposes previously hidden functionality.
'''
# do not replace with self._cache.clear() -- leaves terrible
# state for shallow copies.
self._cache = {}
@overload
def getOffsetBySite(
self,
site: stream.Stream | None,
*,
returnSpecial: t.Literal[False] = False,
) -> OffsetQL:
return 0.0 # dummy until Astroid #1015 is fixed. Replace with ...
@overload
def getOffsetBySite(
self,
site: stream.Stream | None,
*,
returnSpecial: bool = False,
) -> OffsetQL | OffsetSpecial:
return 0.0 # dummy until Astroid #1015 is fixed. Replace with ...
# using bool instead of t.Literal[True] because of
def getOffsetBySite(
self,
site: stream.Stream | None,
*,
returnSpecial: bool = False,
) -> OffsetQL | OffsetSpecial:
'''
If this class has been registered in a container such as a Stream,
that container can be provided here, and the offset in that object
can be returned.
>>> n = note.Note('A-4') # a Music21Object
>>> n.offset = 30
>>> n.getOffsetBySite(None)
30.0
>>> s1 = stream.Stream()
>>> s1.id = 'containingStream'
>>> s1.insert(20 / 3, n)
>>> n.getOffsetBySite(s1)
Fraction(20, 3)
>>> float(n.getOffsetBySite(s1))
6.6666...
n.getOffsetBySite(None) should still return 30.0
>>> n.getOffsetBySite(None)
30.0
If the Stream does not contain the element and the element is not derived from
an element that does, then a SitesException is raised:
>>> s2 = stream.Stream()
>>> s2.id = 'notContainingStream'
>>> n.getOffsetBySite(s2)
Traceback (most recent call last):
music21.sites.SitesException: an entry for this object <music21.note.Note A-> is not
stored in stream <music21.stream.Stream notContainingStream>
Consider this use of derivations:
>>> import copy
>>> nCopy = copy.deepcopy(n)
>>> nCopy.derivation
<Derivation of <music21.note.Note A-> from <music21.note.Note A-> via '__deepcopy__'>
>>> nCopy.getOffsetBySite(s1)
Fraction(20, 3)
nCopy can still find the offset of `n` in `s1`!
This is the primary difference between element.getOffsetBySite(stream)
and stream.elementOffset(element)
>>> s1.elementOffset(nCopy)
Traceback (most recent call last):
music21.sites.SitesException: an entry for this object ... is not
stored in stream <music21.stream.Stream containingStream>
If the object is stored at the end of the Stream, then the highest time
is usually returned:
>>> s3 = stream.Stream()
>>> n3 = note.Note(type='whole')
>>> s3.append(n3)
>>> rb = bar.Barline()
>>> s3.storeAtEnd(rb) # s3.rightBarline = rb would do the same...
>>> rb.getOffsetBySite(s3)
4.0
However, setting returnSpecial to True will return OffsetSpecial.AT_END
>>> rb.getOffsetBySite(s3, returnSpecial=True)
<OffsetSpecial.AT_END>
Even with returnSpecial normal offsets are still returned as a float or Fraction:
>>> n3.getOffsetBySite(s3, returnSpecial=True)
0.0
* Changed in v7: stringReturns renamed to returnSpecial.
Returns an OffsetSpecial Enum.
'''
if site is None:
return self._naiveOffset
try:
a = None
tryOrigin: Music21Object = self
originMemo = set()
maxSearch = 100
while a is None:
try:
a = site.elementOffset(tryOrigin, returnSpecial=returnSpecial)
except AttributeError as ae:
raise SitesException(
f'You were using {site!r} as a site, when it is not a Stream...'
) from ae
except Music21Exception as e: # currently StreamException, but will change
if tryOrigin in site._endElements: