Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a Python class instance if deepcopy() does not work?

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?

like image 327
patapouf_ai Avatar asked Jan 19 '18 10:01

patapouf_ai


People also ask

How do I copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy. deepcopy(c) then vars(c2) == {'a': 11, 'r': 2} and vars(c) == {'a': 11, 'r': 2} but the traceback your are reporting wouldn't be produced by the class definition you gave...

How do you copy a Deepcopy in Python?

To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.

Why is Deepcopy needed Python?

The deepcopy() function avoids these problems by: keeping a memo dictionary of objects already copied during the current copying pass; and. letting user-defined classes override the copying operation or the set of components copied.


Video Answer


1 Answers

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' .

like image 175
Usman Avatar answered Oct 08 '22 07:10

Usman