Skip to content

Commit

Permalink
Speed up __contains__ by 2x and deprecate hasElement
Browse files Browse the repository at this point in the history
  • Loading branch information
TimFelixBeyer authored Jul 8, 2023
1 parent 2a28ab1 commit d43ec76
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions music21/stream/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 783,7 @@ def last(self) -> M21ObjType | None:
except IndexError:
return None

def __contains__(self, el):
def __contains__(self, el: base.Music21Object) -> bool:
'''
Returns True if `el` is in the stream (compared with Identity) and False otherwise.

Expand Down Expand Up @@ -811,8 811,11 @@ def __contains__(self, el):
>>> nC2 in s.elements
True
'''
return (any(sEl is el for sEl in self._elements)
or any(sEl is el for sEl in self._endElements))
# Should be the fastest implementation of this naive check, compare with
# https://stackoverflow.com/questions/44802682/python-any-unexpected-performance
return (id(el) in self._offsetDict
or any(True for sEl in self._elements if sEl is el)
or any(True for sEl in self._endElements if sEl is el))

@property
def elements(self) -> tuple[M21ObjType, ...]:
Expand Down Expand Up @@ -1433,7 1436,8 @@ def mergeAttributes(self, other: base.Music21Object):
'definesExplicitPageBreaks', '_atSoundingPitch', '_mutable'):
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))


@deprecated('v10', 'v11', 'use `obj in stream` instead')
def hasElement(self, obj: base.Music21Object) -> bool:
'''
Return True if an element, provided as an argument, is contained in
Expand All @@ -1449,16 1453,7 @@ def hasElement(self, obj: base.Music21Object) -> bool:
>>> s.hasElement(n1)
True
'''
if id(obj) in self._offsetDict:
return True

for e in self._elements:
if e is obj: # pragma: no cover
return True
for e in self._endElements:
if e is obj: # pragma: no cover
return True
return False
return obj in self

def hasElementOfClass(self, className, forceFlat=False):
'''
Expand Down

0 comments on commit d43ec76

Please sign in to comment.