Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f0e3569

Browse files
committed
Refactor the copy dispatcher code in copy.py. Simplifies and shortens
the code by grouping common cases together.
1 parent 99842b6 commit f0e3569

1 file changed

Lines changed: 17 additions & 35 deletions

File tree

Lib/copy.py

Lines changed: 17 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -97,44 +97,26 @@ def copy(x):
9797

9898
_copy_dispatch = d = {}
9999

100-
def _copy_atomic(x):
100+
def _copy_immutable(x):
101101
return x
102-
d[types.NoneType] = _copy_atomic
103-
d[types.IntType] = _copy_atomic
104-
d[types.LongType] = _copy_atomic
105-
d[types.FloatType] = _copy_atomic
106-
d[types.BooleanType] = _copy_atomic
107-
try:
108-
d[types.ComplexType] = _copy_atomic
109-
except AttributeError:
110-
pass
111-
d[types.StringType] = _copy_atomic
112-
try:
113-
d[types.UnicodeType] = _copy_atomic
114-
except AttributeError:
115-
pass
116-
try:
117-
d[types.CodeType] = _copy_atomic
118-
except AttributeError:
119-
pass
120-
d[types.TypeType] = _copy_atomic
121-
d[types.XRangeType] = _copy_atomic
122-
d[types.ClassType] = _copy_atomic
123-
d[types.BuiltinFunctionType] = _copy_atomic
124-
125-
def _copy_list(x):
126-
return x[:]
127-
d[types.ListType] = _copy_list
128-
129-
def _copy_tuple(x):
130-
return x[:]
131-
d[types.TupleType] = _copy_tuple
132-
133-
def _copy_dict(x):
102+
for t in (types.NoneType, int, long, float, bool, str, tuple,
103+
frozenset, type, xrange, types.ClassType,
104+
types.BuiltinFunctionType):
105+
d[t] = _copy_immutable
106+
for name in ("ComplexType", "UnicodeType", "CodeType"):
107+
t = getattr(types, name, None)
108+
if t is not None:
109+
d[t] = _copy_immutable
110+
111+
def _copy_with_constructor(x):
112+
return type(x)(x)
113+
for t in (list, dict, set):
114+
d[t] = _copy_with_constructor
115+
116+
def _copy_with_copy_method(x):
134117
return x.copy()
135-
d[types.DictionaryType] = _copy_dict
136118
if PyStringMap is not None:
137-
d[PyStringMap] = _copy_dict
119+
d[PyStringMap] = _copy_with_copy_method
138120

139121
def _copy_inst(x):
140122
if hasattr(x, '__copy__'):

0 commit comments

Comments
 (0)