Python Forum
Why is the copy method name in python list copy and not `__copy__`? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why is the copy method name in python list copy and not `__copy__`? (/thread-41894.html)



Why is the copy method name in python list copy and not `__copy__`? - YouHoGeon - Apr-04-2024

Why is the name of copy method in python list copy and not __copy__?

As a result, I confirmed that separate exception handling logic was written for list (or dict, set, bytearray) inside the copy module.
#  https://github.com/python/cpython/blob/main/Lib/copy.py
def copy(x):
    cls = type(x)

    copier = _copy_dispatch.get(cls) # Code for a list that does not have a __copy__ method.
    if copier:
        return copier(x)

    # ...

    copier = getattr(cls, "__copy__", None)
    if copier is not None:
        return copier(x)

    # ...

_copy_dispatch = d = {}

# ...

d[list] = list.copy
This also applies to the __deepcopy__ method. (Even though list has a list.copy (not __copy__) method, there is no list.deepcopy method, so the copy module implements it.)

def _deepcopy_list(x, memo, deepcopy=deepcopy):
    y = []
    memo[id(x)] = y
    append = y.append
    for a in x:
        append(deepcopy(a, memo))
    return y
d[list] = _deepcopy_list
I am curious about the following:

Why is the copy method name in list copy and not __copy__?
Why is the deepcopy logic of list implemented in the copy module and not list.__deepcopy__?
I think that if list had __copy__ and __deepcopy__ methods, the exception handling code in the copy module would go away and consistency would be maintained. But there must be a reason why that wasn't done, and I'm curious as to why?


RE: Why is the copy method name in python list copy and not `__copy__`? - deanhystad - Apr-04-2024

How would __copy__() be called? There is no copy operator, nor is there an implicit need like __str__() used when printing an object.


RE: Why is the copy method name in python list copy and not `__copy__`? - YouHoGeon - Apr-04-2024

(Apr-04-2024, 01:10 AM)deanhystad Wrote: How would __copy__() be called? There is no copy operator, nor is there an implicit need like __str__() used when printing an object.

It can be called through the copy module. Of course, I'm not sure if that's an elegant way to do it, and I'm not dissatisfied with having a method named copy on the list.
Because list copy is a frequently used function, I agree if it is implemented as a list method without a copy module.
However, I was wondering why this (inconsistent) difference occurred because other data structures (such as array) have a __copy__ method rather than a copy method.