https://docs.python.jp/3/library/copy.html
Returns a shallow copy of x.
There is no "how". In other words, the specifications are not really written.
Special methods
__copy__ ()
and__deepcopy__ ()
can be defined to define a class-specific copy implementation.
So is there this method in the list?
>>> lst = [1, 2, 3]
>>> lst.__copy__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__copy__'
There isn't.
Below is the implementation of copy.copy ()
in Python 3.6.1.
def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
try:
issc = issubclass(cls, type)
except TypeError: # cls is not a class
issc = False
if issc:
# treat it as a regular class:
return _copy_immutable(x)
copier = getattr(cls, "__copy__", None)
if copier:
return copier(x)
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error("un(shallow)copyable object of type %s" % cls)
if isinstance(rv, str):
return x
return _reconstruct(x, None, *rv)
_copy_dispatch = d = {}
def _copy_immutable(x):
return x
for t in (type(None), int, float, bool, complex, str, tuple,
bytes, frozenset, type, range, slice,
types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
t = getattr(types, "CodeType", None)
if t is not None:
d[t] = _copy_immutable
d[list] = list.copy
d[dict] = dict.copy
d[set] = set.copy
d[bytearray] = bytearray.copy
...
copy.copy ()
holds a function in the dictionary that realizes shallow copy (and deep copy) in each built-in data type in advance, and if it is not registered in the dictionary, the__copy__ ()
method Look for.
After that, it seems to behave based on the rules related to the pickle
module, but it is omitted because it exceeds the assumptions of this paper. Corresponds to the following part of the document:
The class can use the same interface that it uses to control pickle to control copying. See the module pickle description for information on these methods. In fact, the copy module uses the picle function registered by the copyreg module.
Aside from that, the source code considers copy.copy (lst)
to be equivalent to lst.copy ()
.
By the way, there is no such thing as list.copy ()
in Python 2 series, and lst [:]
is used instead. You may see lst [:]
relatively often in older documents that have been migrated from 2 to 3.
Recommended Posts