[PYTHON] What is copy.copy ()


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)

        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)
        reductor = getattr(x, "__reduce_ex__", None)
        if reductor:
            rv = reductor(4)
            reductor = getattr(x, "__reduce__", None)
            if reductor:
                rv = reductor()
                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

What is copy.copy ()
What is namespace
What is Django? .. ..
What is dotenv?
What is POSIX?
What is Linux
What is klass?
What is SALOME?
What is Linux?
What is python
What is hyperopt?
What is Linux
What is pyvenv
What is __call__
What is Linux
What is Python
What is Raspberry Pi?
[Python] What is Pipeline ...
What is Calmar Ratio?
What is a terminal?
[PyTorch Tutorial ①] What is PyTorch?
What is hyperparameter tuning?
What is a hacker?
What is JSON? .. [Note]
What is Linux for?
What is a pointer?
What is ensemble learning?
What is TCP / IP?
What is Python's __init__.py?
What is an iterator?
What is UNIT-V Linux?
[Python] What is virtualenv
What is machine learning?
What is Minisum or Minimax?
What is Linux? [Command list]
What is Logistic Regression Analysis?
What is the activation function?
What is the Linux kernel?
What is an instance variable?
What is a decision tree?
What is a Context Switch?
What is Google Cloud Dataflow?
[DL] What is weight decay?
[Python] Python and security-① What is Python?
What is a super user?
Competitive programming is what (bonus)
[Python] * args ** What is kwrgs?
What is a system call
[Definition] What is a framework?
What is the interface for ...
What is Project Euler 3 Acceleration?
What is a callback function?
What is the Callback function?
What is a python map?
What is your "Tanimoto coefficient"?
Python Basic Course (1 What is Python)
[Python] What is a zip function?
[Python] What is a with statement?
What is labeling in financial forecasting?
What is Reduced Rank Ridge Regression?
What is Azure Automation Update Management?