Music21 base classes for Stream objects and elements contained within them. 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'>
Alternatively, after doing a complete import, these classes are available
under the module "base":
>>> from music21 import *
>>> base.Music21Object
<class 'music21.base.Music21Object'>
Inherits from: JSONSerializer
Base class for all music21 objects. All music21 objects encode 7 pieces of information: (1) id: identification string unique to the objects container (optional) (2) groups: a Groups object: which is a list of strings identifying internal subcollections (voices, parts, selections) to which this element belongs (3) duration: Duration object representing the length of the object (4) parent: a reference or weakreference to a currently active Location (5) offset: a floating point value, generally in quarter lengths, specifying the position of the object in parent (6) priority: int representing the position of an object among all objects at the same offset. Contexts, locations, and offsets are stored in a DefinedContexts object. Locations specify connections of this object to one location in a Stream subclass. Contexts are weakrefs for current objects that are associated with this object (similar to locations but without an offset)
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)
Music21Object attributes
- 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
>>> from music21 import * >>> tc = clef.TrebleClef() >>> tc.classSortOrder 0 >>> ks = key.KeySignature(3) >>> ks.classSortOrder 1New classes can define their own default classSortOrder
>>> class ExampleClass(base.Music21Object): ... classSortOrderDefault = 5 ... >>> ec1 = ExampleClass() >>> ec1.classSortOrder 5
- id¶
- Unique identification string.
- groups¶
- An instance of a Group object.
Music21Object properties
- activeSite¶
- A reference to the most-recent object used to contain this object. In most cases, this will be a Stream or Stream sub-class. In most cases, an object’s parent attribute is automatically set when an the object is attached to a Stream.
- beat¶
Return the beat of this Note as found in the most recently positioned Measure. Beat values count from 1 and contain a floating-point designation between 0 and 1 to show proportional progress through the beat.
>>> from music21 import * >>> n = note.Note() >>> n.quarterLength = .5 >>> m = stream.Measure() >>> m.timeSignature = meter.TimeSignature('3/4') >>> m.repeatAppend(n, 6) >>> [m.notes[i].beat for i in range(6)] [1.0, 1.5, 2.0, 2.5, 3.0, 3.5] >>> m.timeSignature = meter.TimeSignature('6/8') >>> [m.notes[i].beat for i in range(6)] [1.0, 1.3333333..., 1.666666666..., 2.0, 2.33333333..., 2.66666...]
- beatDuration¶
Return a Duration of the beat active for this Note as found in the most recently positioned Measure.
>>> from music21 import * >>> n = note.Note() >>> n.quarterLength = .5 >>> m = stream.Measure() >>> m.timeSignature = meter.TimeSignature('3/4') >>> m.repeatAppend(n, 6) >>> [m.notes[i].beatDuration.quarterLength for i in range(6)] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0] >>> m.timeSignature = meter.TimeSignature('6/8') >>> [m.notes[i].beatDuration.quarterLength for i in range(6)] [1.5, 1.5, 1.5, 1.5, 1.5, 1.5]
- beatStr¶
Return a string representation of the beat of this Note as found in the most recently positioned Measure. Beat values count from 1 and contain a fractional designation to show progress through the beat.
>>> from music21 import * >>> n = note.Note() >>> n.quarterLength = .5 >>> m = stream.Measure() >>> m.timeSignature = meter.TimeSignature('3/4') >>> m.repeatAppend(n, 6) >>> [m.notes[i].beatStr for i in range(6)] ['1', '1 1/2', '2', '2 1/2', '3', '3 1/2'] >>> m.timeSignature = meter.TimeSignature('6/8') >>> [m.notes[i].beatStr for i in range(6)] ['1', '1 1/3', '1 2/3', '2', '2 1/3', '2 2/3']
- beatStrength¶
Return the metrical accent of this Note in the most recently positioned Measure. Accent values are between zero and one, and are derived from the local TimeSignature’s accent MeterSequence weights. If the offset of this Note does not match a defined accent weight, a minimum accent weight will be returned.
>>> from music21 import * >>> n = note.Note() >>> n.quarterLength = .5 >>> m = stream.Measure() >>> m.timeSignature = meter.TimeSignature('3/4') >>> m.repeatAppend(n, 6) >>> [m.notes[i].beatStrength for i in range(6)] [1.0, 0.25, 0.5, 0.25, 0.5, 0.25] >>> m.timeSignature = meter.TimeSignature('6/8') >>> [m.notes[i].beatStrength for i in range(6)] [1.0, 0.25, 0.25, 0.5, 0.25, 0.25]
- classes¶
Returns a list containing the names (strings, not objects) of classes that this object belongs to – starting with the object’s class name and going up the mro() for the object. Very similar to Perl’s @ISA array:
>>> from music21 import * >>> q = note.QuarterNote() >>> q.classes[:5] ['QuarterNote', 'Note', 'NotRest', 'GeneralNote', 'Music21Object']Example: find GClefs that are not Treble clefs (or treble 8vb, etc.):
>>> s = stream.Stream() >>> s.insert(10, clef.GClef()) >>> s.insert(20, clef.TrebleClef()) >>> s.insert(30, clef.FrenchViolinClef()) >>> s.insert(40, clef.Treble8vbClef()) >>> s.insert(50, clef.BassClef()) >>> s2 = stream.Stream() >>> for t in s: ... if 'GClef' in t.classes and 'TrebleClef' not in t.classes: ... s2.insert(t) >>> s2.show('text') {10.0} <music21.clef.GClef object at 0x...> {30.0} <music21.clef.FrenchViolinClef object at 0x...>
- duration¶
- Get and set the duration of this object as a Duration object.
- measureNumberLocal¶
- Return the measure number of a Measure that contains this object.
- offset¶
The offset property returns the position of this object from the start of its most recently referenced container (a Stream or Stream sub-class found in activeSite) in quarter lengths. It can also set the offset for the object if no container has been set
>>> from music21 import * >>> n1 = note.Note() >>> n1.id = 'hi' >>> n1.offset = 20 >>> n1.offset 20.0 >>> s1 = stream.Stream() >>> s1.append(n1) >>> n1.offset 0.0 >>> s2 = stream.Stream() >>> s2.insert(30.5, n1) >>> n1.offset 30.5 >>> n2 = s1.getElementById('hi') >>> n2 is n1 True >>> n2.offset 0.0 >>> for thisElement in s2: ... print thisElement.offset 30.5
- priority¶
Get and set the priority integer value. Priority specifies the order of processing from left (lowest number) to right (highest number) of objects at the same offset. For instance, if you want a key change and a clef change to happen at the same time but the key change to appear first, then set: keySigElement.priority = 1; clefElement.priority = 2 this might be a slightly counterintuitive numbering of priority, but it does mean, for instance, if you had two elements at the same offset, an allegro tempo change and an andante tempo change, then the tempo change with the higher priority number would apply to the following notes (by being processed second). Default priority is 0; thus negative priorities are encouraged to have Elements that appear non-priority set elements. In case of tie, there are defined class sort orders defined in music21.base.CLASS_SORT_ORDER. For instance, a key signature change appears before a time signature change before a note at the same offset. This produces the familiar order of materials at the start of a musical score.
>>> from music21 import * >>> a = base.Music21Object() >>> a.priority = 3 >>> a.priority = 'high' Traceback (most recent call last): ElementException: priority values must be integers.Properties inherited from JSONSerializer: json
Music21Object methods
- searchParentByAttr(attrName)¶
- If this element is contained within a Stream or other Music21 element, searchParentByAttr() permits searching attributes of higher-level objects. The first encountered match is returned, or None if no match. All parents are recursively searched upward.
- getContextAttr(attr)¶
Given the name of an attribute, search Conctexts and return the best match.
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> aObj.attr1 = 'test' >>> a = Music21Object() >>> a.addContext(aObj) >>> a.getContextAttr('attr1') 'test'
- setContextAttr(attrName, value)¶
Given the name of an attribute, search Conctexts and return the best match.
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> aObj.attr1 = 'test' >>> a = Music21Object() >>> a.addContext(aObj) >>> a.getContextAttr('attr1') 'test' >>> a.setContextAttr('attr1', 3000) >>> a.getContextAttr('attr1') 3000
- addContext(obj)¶
Add an ojbect to the DefinedContexts object. For adding a location, use addLocation().
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> aObj.attr1 = 'test' >>> a = Music21Object() >>> a.addContext(aObj) >>> a.getContextAttr('attr1') 'test'
- addLocation(site, offset)¶
Add a location to the DefinedContexts object. The supplied object is a reference to the object (the site) that contains an offset of this object. For example, if this Music21Object was Note, the site would be a Stream (or Stream subclass) and the offset would be a number for the offset. This is only for advanced location method and is not a complete or sufficient way to add an object to a Stream.
>>> from music21 import note, stream >>> s = stream.Stream() >>> n = note.Note() >>> n.addLocation(s, 10)
- addLocationAndActiveSite(offset, activeSite, activeSiteWeakRef=None)¶
This method is for advanced usage, generally as a speedup tool that adds a new location element and a new activeSite. Formerly called by Stream.insert – this saves some dual processing. Does not do safety checks that the siteId doesn’t already exist etc., because that is done earlier. This speeds up things like stream.getElementsById substantially. Testing script (N.B. manipulates Stream._elements directly – so not to be emulated)
>>> from stream import Stream >>> st1 = Stream() >>> o1 = Music21Object() >>> st1_wr = common.wrapWeakref(st1) >>> offset = 20.0 >>> st1._elements = [o1] >>> o1.addLocationAndActiveSite(offset, st1, st1_wr) >>> o1.activeSite is st1 True >>> o1.getOffsetBySite(st1) 20.0
- freezeIds()¶
Temporarily replace are stored keys with a different value.
>>> aM21Obj = Music21Object() >>> bM21Obj = Music21Object() >>> aM21Obj.offset = 30 >>> aM21Obj.getOffsetBySite(None) 30.0 >>> bM21Obj.addLocationAndActiveSite(50, aM21Obj) >>> bM21Obj.activeSite != None True >>> oldParentId = bM21Obj._activeSiteId >>> bM21Obj.freezeIds() >>> newParentId = bM21Obj._activeSiteId >>> oldParentId == newParentId False
- getAllContextsByClass(className, found=None, idFound=None, memo=None)¶
- Search both DefinedContexts as well as associated objects to find all matchinging classes. Returns [] if not match is found.
- getContextByClass(className, serialReverseSearch=True, callerFirst=None, sortByCreationTime=False, prioritizeActiveSite=True, memo=None)¶
- Search both DefinedContexts as well as associated objects to find a matching class. Returns None if not match is found. The a reference to the caller is required to find the offset of the object of the caller. This is needed for serialReverseSearch. The caller may be a DefinedContexts reference from a lower-level object. If so, we can access the location of that lower-level object. However, if we need a flat representation, the caller needs to be the source Stream, not its DefinedContexts reference. The callerFirst is the first object from which this method was called. This is needed in order to determine the final offset from which to search. The prioritizeActiveSite parameter searches the objects parent before any other object.
- getOffsetBySite(site)¶
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. Note that this is different than the getOffsetByElement() method on Stream in that this can never access the flat representation of a Stream.
>>> from music21 import * >>> a = base.Music21Object() >>> a.offset = 30 >>> a.getOffsetBySite(None) 30.0 >>> s1 = stream.Stream() >>> s1.insert(20.5, a) >>> a.getOffsetBySite(s1) 20.5 >>> s2 = stream.Stream() >>> a.getOffsetBySite(s2) ... DefinedContextsException: Could not find the object with id ...
- getSiteIds()¶
- Return a list of all site Ids, or the id() value of the sites of this object.
- getSites()¶
Return a list of all objects that store a location for this object. Will remove None, the default empty site placeholder.
>>> from music21 import note, stream >>> s1 = stream.Stream() >>> s2 = stream.Stream() >>> n = note.Note() >>> s1.append(n) >>> s2.append(n) >>> n.getSites() == [None, s1, s2] True
- getSpannerSites()¶
Return a list of all sites that are Spanner or Spanner subclasses. This provides a way for objects to be aware of what Spanners they reside in. Note that Spanners are not Stream subclasses, but Music21Objects that are composed with a specialized Stream subclass.
>>> from music21 import * >>> n1 = note.Note() >>> n2 = note.Note() >>> sp1 = spanner.Slur(n1, n2) >>> n1.getSpannerSites() == [sp1] True >>> sp2 = spanner.Slur(n2, n1) >>> n2.getSpannerSites() == [sp1, sp2] True
- hasContext(obj)¶
Return a Boolean if an object reference is stored in the object’s DefinedContexts object. This checks both all locations as well as all sites.
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> aObj.attr1 = 'test' >>> a = Music21Object() >>> a.addContext(aObj) >>> a.hasContext(aObj) True >>> a.hasContext(None) True >>> a.hasContext(45) False
- mergeAttributes(other)¶
- Merge all elementary, static attributes. Namely, id and groups attributes from another music21 object. Can be useful for copy-like operations.
- purgeLocations()¶
- Remove references to all locations in objects that no longer exist.
- removeLocationBySite(site)¶
Remove a location in the DefinedContexts object. This is only for advanced location method and is not a complete or sufficient way to remove an object from a Stream.
>>> from music21 import note, stream >>> s = stream.Stream() >>> n = note.Note() >>> n.addLocation(s, 10) >>> n.activeSite = s >>> n.removeLocationBySite(s) >>> n.activeSite == None True
- removeLocationBySiteId(siteId)¶
Remove a location in the DefinedContexts object by id.
>>> from music21 import note, stream >>> s = stream.Stream() >>> n = note.Note() >>> n.addLocation(s, 10) >>> n.activeSite = s >>> n.removeLocationBySiteId(id(s)) >>> n.activeSite == None True
- setOffsetBySite(site, value)¶
Direct access to the DefinedContexts setOffsetBySite() method. This should only be used for advanced processing of known site that already has been added.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> a = Music21Object() >>> a.addLocation(aSite, 20) >>> a.setOffsetBySite(aSite, 30)
- show(fmt=None, app=None)¶
- Displays an object in a format provided by the fmt argument or, if not provided, the format set in the user’s Environment Valid formats include (but are not limited to): xml (musicxml) text lily.png lily.pdf
- splitAtDurations()¶
Takes a Note and returns a list of Notes with only a single duration.DurationUnit in each. Ties are added.
>>> from music21 import * >>> a = note.Note() >>> a.duration.clear() # remove defaults >>> a.duration.addDurationUnit(duration.Duration('half')) >>> a.duration.quarterLength 2.0 >>> a.duration.addDurationUnit(duration.Duration('whole')) >>> a.duration.quarterLength 6.0 >>> b = a.splitAtDurations() >>> b[0].pitch == b[1].pitch True >>> b[0].duration.type 'half' >>> b[1].duration.type 'whole'
- splitAtQuarterLength(quarterLength, retainOrigin=True, addTies=True, displayTiedAccidentals=False)¶
Split an Element into two Elements at a provided QuarterLength into the Element.
>>> from music21 import * >>> a = note.Note('C#5') >>> a.duration.type = 'whole' >>> a.articulations = [articulations.Staccato()] >>> a.lyric = 'hi' >>> a.expressions = [expressions.Mordent(), expressions.Trill(), expressions.Fermata()] >>> b, c = a.splitAtQuarterLength(3) >>> b.duration.type 'half' >>> b.duration.dots 1 >>> b.duration.quarterLength 3.0 >>> b.articulations [<music21.articulations.Staccato>] >>> b.lyric 'hi' >>> b.expressions [<music21.expressions.Mordent>, <music21.expressions.Trill>] >>> c.duration.type 'quarter' >>> c.duration.dots 0 >>> c.duration.quarterLength 1.0 >>> c.articulations [] >>> c.lyric >>> c.expressions [<music21.expressions.Trill>, <music21.expressions.Fermata>]
- splitByQuarterLengths(quarterLengthList, addTies=True, displayTiedAccidentals=False)¶
Given a list of quarter lengths, return a list of Music21Object objects, copied from this Music21Object, that are partitioned and tied with the specified quarter length list durations.
>>> from music21 import * >>> n = note.Note() >>> n.quarterLength = 3 >>> post = n.splitByQuarterLengths([1,1,1]) >>> [n.quarterLength for n in post] [1, 1, 1]
- unfreezeIds()¶
Restore keys to be the id() of the object they contain
>>> aM21Obj = Music21Object() >>> bM21Obj = Music21Object() >>> aM21Obj.offset = 30 >>> aM21Obj.getOffsetBySite(None) 30.0 >>> bM21Obj.addLocationAndActiveSite(50, aM21Obj) >>> bM21Obj.activeSite != None True >>> oldParentId = bM21Obj._activeSiteId >>> bM21Obj.freezeIds() >>> newParentId = bM21Obj._activeSiteId >>> oldParentId == newParentId False >>> bM21Obj.unfreezeIds() >>> postParentId = bM21Obj._activeSiteId >>> oldParentId == postParentId True
- unwrapWeakref()¶
Public interface to operation on DefinedContexts.
>>> aM21Obj = Music21Object() >>> bM21Obj = Music21Object() >>> aM21Obj.offset = 30 >>> aM21Obj.getOffsetBySite(None) 30.0 >>> aM21Obj.addLocationAndActiveSite(50, bM21Obj) >>> aM21Obj.unwrapWeakref()
- wrapWeakref()¶
Public interface to operation on DefinedContexts.
>>> aM21Obj = Music21Object() >>> bM21Obj = Music21Object() >>> aM21Obj.offset = 30 >>> aM21Obj.getOffsetBySite(None) 30.0 >>> aM21Obj.addLocationAndActiveSite(50, bM21Obj) >>> aM21Obj.unwrapWeakref() >>> aM21Obj.wrapWeakref()
- write(fmt=None, fp=None)¶
- Write a file. A None file path will result in temporary file
Methods inherited from JSONSerializer: jsonAttributes(), jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()
Inherits from: Music21Object, JSONSerializer
An element wraps any object that is not a Music21Object, so that that object can be positioned within a Stream. The object stored within ElementWrapper is available from the the obj attribute. Providing an object at initialization is mandatory.
ElementWrapper attributes
- obj¶
- The object this wrapper wraps.
Attributes inherited from Music21Object: classSortOrder
ElementWrapper properties
- duration¶
Gets the duration of the ElementWrapper (if separately set), but normal returns the duration of the component object if available, otherwise returns None.
>>> import note >>> n = note.Note('F#') >>> n.quarterLength = 2.0 >>> n.duration.quarterLength 2.0 >>> el1 = ElementWrapper(n) >>> el1.duration.quarterLength 2.0 ADVANCED FEATURE TO SET DURATION OF ELEMENTS AND STREAMS SEPARATELY >>> class KindaStupid(object): ... pass >>> ks1 = ElementWrapper(KindaStupid()) >>> ks1.obj.duration Traceback (most recent call last): AttributeError: 'KindaStupid' object has no attribute 'duration' >>> import duration >>> ks1.duration = duration.Duration("whole") >>> ks1.duration.quarterLength 4.0 >>> ks1.obj.duration # still not defined Traceback (most recent call last): AttributeError: 'KindaStupid' object has no attribute 'duration'
- id¶
- No documentation.
- offset¶
- Get the offset for the activeSite.
Properties inherited from Music21Object: activeSite, beat, beatDuration, beatStr, beatStrength, classes, measureNumberLocal, priority
Properties inherited from JSONSerializer: json
ElementWrapper methods
- getId()¶
- No documentation.
- isTwin(other)¶
A weaker form of equality. a.isTwin(b) is true if a and b store either the same object OR objects that are equal and a.groups == b.groups and a.id == b.id (or both are none) and duration are equal. but does not require position, priority, or activeSite to be the same In other words, is essentially the same object in a different context
>>> import note >>> aE = ElementWrapper(obj = note.Note("A-")) >>> aE.id = "aflat-Note" >>> aE.groups.append("out-of-range") >>> aE.offset = 4.0 >>> aE.priority = 4 >>> bE = copy.copy(aE) >>> aE is bE False >>> aE == bE True >>> aE.isTwin(bE) True >>> bE.offset = 14.0 >>> bE.priority = -4 >>> aE == bE False >>> aE.isTwin(bE) True
- setId(newId)¶
- No documentation.
Methods inherited from Music21Object: addContext(), addLocation(), addLocationAndActiveSite(), freezeIds(), getAllContextsByClass(), getContextAttr(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), mergeAttributes(), purgeLocations(), removeLocationBySite(), removeLocationBySiteId(), searchParentByAttr(), setContextAttr(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unfreezeIds(), unwrapWeakref(), wrapWeakref(), write()
Methods inherited from JSONSerializer: jsonAttributes(), jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()
An object, stored within a Music21Object, that stores references to a collection of objects that may be contextually relevant. Some of these objects are locations; these DefinedContext additional store an offset value, used for determining position within a Stream. DefinedContexts are one of many ways that context can be found; context can also be found through searching (using objects in DefinedContexts). All defined contexts are stored as dictionaries in a dictionary. The outermost dictionary stores objects
DefinedContexts methods
- add(obj, offset=None, timeValue=None, idKey=None)¶
- Add a reference to the DefinedContexts collection. if offset is None, it is interpreted as a context if offset is a value, it is intereted as location The timeValue argument is used to store the time at which an object is added to locations. This is not the same as offset
- clear()¶
- Clear all stored data.
- freezeIds()¶
Temporarily replace are stored keys with a different value.
>>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> aContexts.add(bObj) >>> oldKeys = aContexts._definedContexts.keys() >>> aContexts.freezeIds() >>> newKeys = aContexts._definedContexts.keys() >>> oldKeys == newKeys False
- get(locationsTrail=False, sortByCreationTime=False, priorityTarget=None, autoPurge=True)¶
Get references; unwrap from weakrefs; order, based on dictionary keys, is from most recently added to least recently added. The locationsTrail option forces locations to come after all other defined contexts. The sortByCreationTime option will sort objects by creation time, where most-recently assigned objects are returned first. If priorityTarget is defined, this object will be placed first in the list of objects. If autoPurge is True, this method automatically removes dead weak-refs. Thus, every time locations are gotten, any dead weakrefs are removed. This provides a modest performance boost.
>>> from music21 import * >>> import time >>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> cObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(cObj, 345) # a locations >>> #time.sleep(.05) >>> aContexts.add(aObj) >>> #time.sleep(.05) >>> aContexts.add(bObj) >>> aContexts.get() == [cObj, aObj, bObj] True >>> aContexts.get(locationsTrail=True) == [aObj, bObj, cObj] True >>> aContexts.get(sortByCreationTime=True) == [bObj, aObj, cObj] True
- getAllByClass(className, found=None, idFound=None, memo=None)¶
Return all known references of a given class found in any association with this DefinedContexts. This will recursively search the defined contexts of existing defined contexts, and return a list of all objects that match the given class.
>>> from music21 import * >>> class Mock(Music21Object): pass >>> import time >>> aObj = Mock() >>> bObj = Mock() >>> dc = music21.DefinedContexts() >>> dc.add(aObj) >>> dc.add(bObj) >>> dc.getAllByClass = [aObj, bObj]
- getAttrByName(attrName)¶
Given an attribute name, search all objects and find the first that matches this attribute name; then return a reference to this attribute.
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> aObj.attr1 = 234 >>> bObj = Mock() >>> bObj.attr1 = 98 >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> len(aContexts) 1 >>> aContexts.getAttrByName('attr1') == 234 True >>> aContexts.removeById(id(aObj)) >>> aContexts.add(bObj) >>> aContexts.getAttrByName('attr1') == 98 True
- getByClass(className, serialReverseSearch=True, callerFirst=None, sortByCreationTime=False, prioritizeActiveSite=False, priorityTarget=None, memo=None)¶
Return the most recently added reference based on className. Class name can be a string or the class name. This will recursively search the defined contexts of existing defined contexts. The callerFirst parameters is simply used to pass a reference of the first caller; this is necessary if we are looking within a Stream for a flat offset position. If priorityTarget is specified, this location will be searched first. The prioritizeActiveSite is pased to to any recursively called getContextByClass() calls.
>>> class Mock(Music21Object): pass >>> import time >>> aObj = Mock() >>> bObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> #time.sleep(.05) >>> aContexts.add(bObj) >>> # we get the most recently added object first >>> aContexts.getByClass('mock', sortByCreationTime=True) == bObj True >>> aContexts.getByClass(Mock, sortByCreationTime=True) == bObj True
- getById(id)¶
- Return the object specified by an id. Used for testing and debugging.
- getOffsetByObjectMatch(obj)¶
For a given object return the offset using a direct object match. The stored id value is not used; instead, the id() of both the stored object reference and the supplied objet is used.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cParent = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 23) >>> aLocations.add(bSite, 121.5) >>> aLocations.getOffsetBySite(aSite) 23 >>> aLocations.getOffsetBySite(bSite) 121.5
- getOffsetBySite(site)¶
For a given site return its offset. The None site is permitted. The id() of the site is used to find the offset.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cParent = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 23) >>> aLocations.add(bSite, 121.5) >>> aLocations.getOffsetBySite(aSite) 23 >>> aLocations.getOffsetBySite(bSite) 121.5
- getOffsetBySiteId(siteId)¶
For a given site id, return its offset.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cParent = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 23) >>> aLocations.add(bSite, 121.5) >>> aLocations.getOffsetBySiteId(id(aSite)) 23 >>> aLocations.getOffsetBySiteId(id(bSite)) 121.5
- getOffsets()¶
Return a list of all offsets.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cSite = Mock() >>> dSite = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 0) >>> aLocations.add(cSite) # a context >>> aLocations.add(bSite, 234) # can add at same offset or another >>> aLocations.add(dSite) # a context >>> aLocations.getOffsets() [0, 234]
- getSiteByOffset(offset)¶
For a given offset return the parent # More than one parent may have the same offset; # this can return the last site added by sorting time No - now we use a dict, so there’s no guarantee that the one you want will be there – need orderedDicts!
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cSite = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 23) >>> aLocations.add(bSite, 23121.5) >>> aSite == aLocations.getSiteByOffset(23) True
- getSiteIds()¶
Return a list of all site Ids.
>>> from music21 import * >>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> dc = music21.DefinedContexts() >>> dc.add(aSite, 0) >>> dc.add(bSite) # a context >>> dc.getSiteIds() == [id(aSite)] True
- getSites()¶
Get all defined contexts that are locations; unwrap from weakrefs
>>> from music21 import * >>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj, 234) >>> aContexts.add(bObj, 3000) >>> len(aContexts._locationKeys) == 2 True >>> len(aContexts.getSites()) == 2 True
- getSitesByClass(className)¶
Return sites that match the provided class.
>>> from music21 import * >>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> cObj = stream.Stream() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj, 234) >>> aContexts.add(bObj, 3000) >>> aContexts.add(cObj, 200) >>> aContexts.getSitesByClass(Mock) == [aObj, bObj] True >>> aContexts.getSitesByClass('Stream') == [cObj] True
- hasSiteId(siteId)¶
Return True or False if this DefinedContexts object already has this site id defined as a location
>>> from music21 import * >>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> dc = music21.DefinedContexts() >>> dc.add(aSite, 0) >>> dc.add(bSite) # a context >>> dc.hasSiteId(id(aSite)) True >>> dc.hasSiteId(id(bSite)) False
- isSite(obj)¶
Given an object, determine if it is a site stored in this DefinedContexts. This will return False if the object is simply a context and not a location
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 0) >>> aLocations.add(bSite) # a context >>> aLocations.isSite(aSite) True >>> aLocations.isSite(bSite) False
- purgeLocations()¶
Clean all locations that refer to objects that no longer exist.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cSite = Mock() >>> dSite = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 0) >>> aLocations.add(cSite) # a context >>> del aSite >>> len(aLocations) 2 >>> aLocations.purgeLocations() >>> len(aLocations) 1
- remove(site)¶
Remove the object (a context or location site) specified from DefinedContexts. Object provided can be a location site or a defined context.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cSite = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aSite, 23) >>> len(aContexts) 1 >>> aContexts.add(bSite, 233) >>> len(aContexts) 2 >>> aContexts.add(cSite, 232223) >>> len(aContexts) 3 >>> aContexts.remove(aSite) >>> len(aContexts) 2
- removeById(idKey)¶
- Remove a defined contexts entry by id key, which is id() of the object.
- setAttrByName(attrName, value)¶
Given an attribute name, search all objects and find the first that matches this attribute name; then return a reference to this attribute.
>>> class Mock(Music21Object): attr1=234 >>> aObj = Mock() >>> bObj = Mock() >>> bObj.attr1 = 98 >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> aContexts.add(bObj) >>> aContexts.setAttrByName('attr1', 'test') >>> aContexts.getAttrByName('attr1') == 'test' True
- setOffsetBySite(site, value)¶
Changes the offset of the site specified. Note that this can also be done with add, but the difference is that if the site is not in DefinedContexts, it will raise an exception.
>>> class Mock(Music21Object): pass >>> aSite = Mock() >>> bSite = Mock() >>> cSite = Mock() >>> aLocations = DefinedContexts() >>> aLocations.add(aSite, 23) >>> aLocations.add(bSite, 121.5) >>> aLocations.setOffsetBySite(aSite, 20) >>> aLocations.getOffsetBySite(aSite) 20 >>> aLocations.setOffsetBySite(cSite, 30) Traceback (most recent call last): DefinedContextsException: ...
- setOffsetBySiteId(siteId, value)¶
- Set an offset by siteId. This assumes that the site is valid, is best used for advanced, performance critical usage only. The siteId parameter can be None
- unfreezeIds()¶
Restore keys to be the id() of the object they contain
>>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> cObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> aContexts.add(bObj) >>> aContexts.add(cObj, 200) # a location >>> oldKeys = aContexts._definedContexts.keys() >>> oldLocations = aContexts._locationKeys[:] >>> aContexts.freezeIds() >>> newKeys = aContexts._definedContexts.keys() >>> oldKeys == newKeys False >>> aContexts.unfreezeIds() >>> postKeys = aContexts._definedContexts.keys() >>> postKeys == newKeys False >>> # restored original ids b/c objs are alive >>> sorted(postKeys) == sorted(oldKeys) True >>> oldLocations == aContexts._locationKeys True
- unwrapWeakref()¶
Unwrap any and all weakrefs stored.
>>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> aContexts.add(bObj) >>> common.isWeakref(aContexts.get()[0]) # unwrapping happens False >>> common.isWeakref(aContexts._definedContexts[id(aObj)]['obj']) True >>> aContexts.unwrapWeakref() >>> common.isWeakref(aContexts._definedContexts[id(aObj)]['obj']) False >>> common.isWeakref(aContexts._definedContexts[id(bObj)]['obj']) False
- wrapWeakref()¶
Wrap any and all weakrefs stored.
>>> class Mock(Music21Object): pass >>> aObj = Mock() >>> bObj = Mock() >>> aContexts = DefinedContexts() >>> aContexts.add(aObj) >>> aContexts.add(bObj) >>> aContexts.unwrapWeakref() >>> aContexts.wrapWeakref() >>> common.isWeakref(aContexts._definedContexts[id(aObj)]['obj']) True >>> common.isWeakref(aContexts._definedContexts[id(bObj)]['obj']) True
Inherits from: list
A list of strings used to identify associations that an element might have. Enforces that all elements must be strings
>>> g = Groups()
>>> g.append("hello")
>>> g[0]
'hello'
>>> g.append(5)
Traceback (most recent call last):
GroupException: Only strings can be used as list names
Class that provides JSON output and input routines. Objects can inherit this class directly, or gain its functional through inheriting Music21Object.
JSONSerializer properties
- json¶
- Get or set string JSON data for this object. This method is only available if a JSONSerializer subclass object has been customized and configured by overriding the following methods: jsonAttributes(), jsonComponentFactory().
JSONSerializer methods
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- Given a stored string during JSON serialization, return an object’ The subclass that overrides this method will have access to all modules necessary to create whatever objects necessary.
- jsonPrint()¶
- No documentation.
- jsonRead(fp)¶
- Given a file path, read JSON from a file to this object. Default file extension should be .json. File is opened and closed within this method call.
- jsonWrite(fp, format=True)¶
- Given a file path, write JSON to a file for this object. Default file extension should be .json. File is opened and closed within this method call.