How to copy a class instance in python?

patapouf_ai picture patapouf_ai · Jan 19, 2018 · Viewed 28.5k times · Source

I would like to make a copy of a class instance in python. I tried copy.deepcopy but I get the error message:

RuntimeError: Only Variables created explicitly by the user (graph leaves) support the deepcopy protocol at the moment

So suppose I have something like:

class C(object):
    def __init__(self,a,b, **kwargs):
        self.a=a
        self.b=b
        for x, v in kwargs.items():
            setattr(self, x, v)

c = C(4,5,'r'=2)
c.a = 11
del c.b

And now I want to make an identical deep copy of c, is there an easy way?

Answer

Usman picture Usman · Jan 19, 2018

Yes you can make a copy of class instance using deepcopy:

from copy import deepcopy

c = C(4,5,'r'=2)
d = deepcopy(c)

This creates the copy of class instance 'c' in 'd' .