Skip to content

Commit

Permalink
don't use copy._reconstruct
Browse files Browse the repository at this point in the history
faster to just do our own _IMMUTABLE check first.

looks like a bigger speedup
  • Loading branch information
mscuthbert committed Oct 14, 2022
1 parent 0da76b7 commit 57d0af6
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions music21/common/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
import sys
import textwrap
import time
import types
import typing as t
import weakref

__all__ = [
'flattenList',
Expand Down Expand Up @@ -231,6 +233,15 @@ def runningUnderIPython() -> bool:
# NB -- temp files (tempFile) etc. are in environment.py

# ------------------------------------------------------------------------------
# From copy.py
_IMMUTABLE_DEEPCOPY_TYPES = {
type(None), type(Ellipsis), type(NotImplemented),
int, float, bool, complex, bytes, str,
types.CodeType, type, range,
types.BuiltinFunctionType, types.FunctionType,
weakref.ref, property,
}

def defaultDeepcopy(obj: t.Any, memo=None, *, ignoreAttributes: Iterable[str] = ()):
'''
Unfortunately, it is not possible to do something like::
Expand Down Expand Up @@ -260,13 +271,18 @@ def __deepcopy__(self, memo):
memo = {}

rv = obj.__reduce_ex__(4) # get a protocol 4 reduction
state = rv[2]
func, args, state = rv[:3]
new = func(*args)
memo[id(obj)] = new

# set up reducer to not copy the ignoreAttributes set.
for ignore_attr in ignoreAttributes:
if ignore_attr in state:
state[ignore_attr] = None # atomic copy.
new = copy._reconstruct(obj, memo, *rv) # type: ignore
for attr, value in state.items():
if attr in ignoreAttributes:
setattr(new, attr, None)
elif type(value) in _IMMUTABLE_DEEPCOPY_TYPES:
setattr(new, attr, value)
else:
setattr(new, attr, copy.deepcopy(value, memo))
return new


Expand Down

0 comments on commit 57d0af6

Please sign in to comment.