i am implementing a python class that provides some nested data structure. i want to add support for copying through copy.copy()
and deep copying through copy.deepcopy()
, which, as the docs for the copy module describe, involves writing __copy__()
and __deepcopy__
special methods.
i know how to teach my class to make a copy of itself, but i want to avoid going through __init__()
on the new instance, since __init__()
does some things that my copying logic does not want (or need) to do.
what i ended up with is this method, which works as intended:
def __copy__(self):
cls = type(self)
obj = cls.__new__(cls)
# custom copying logic that populates obj goes here
return obj
my question is: is calling cls.__new__(cls)
the right approach for a __copy__()
implementation that wants to skip __init__()
for the copy? or is there a more "pythonic" approach that i overlooked?