Quantcast
Viewing all articles
Browse latest Browse all 14069

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

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.pydef 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 yd[list] = _deepcopy_list

I am curious about the following:

  1. Why is the copy method name in list copy and not __copy__?
  2. 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?


Viewing all articles
Browse latest Browse all 14069

Trending Articles