AAlon
AAlon

Reputation: 434

Implementing "copy constructor" vs. using copy()

What is generally preferred, in terms of python conventions + speed? something like:

class Object(object):
    def __init__(self, other_object=None):
        if other_object:
            self.value = other_object.value
        else:
            self.value = something

and then

obj = Object(other_object)

or, using copy():

from copy import copy
obj = copy(other_object)

Upvotes: 4

Views: 771

Answers (1)

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

The things are very simple, considering the documentation of the copy module:

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.

So, if you feel that the standard copy() or deepcopy() works slow or has some other issues, just implement one of the methods mentioned above. That way you are sticking to the well-known Python objects copying mechanism, still copying the object the way you want it to be copied.

Upvotes: 5

Related Questions