trouble with copy/deepcopy

ladasky at my-deja.com ladasky at my-deja.com
Mon May 16 15:02:31 EDT 2005


Alexander Zatvornitskiy wrote:
> Hello!
>
> I have trouble with copy/deepcopy. It seems, I just don't understand
something.
> Please explain where things goes wrong and how to do it the right
way.
>
> I have one class:
>
> class Distribution:
>   __gr_on_transp=dict()
>   __ostatok_m=dict()
> and so on
>
> And, I want to make full copy of it:
> d1=Distribution()
> d2=copy.deepcopy(d1)
>
> But, members-dictionaries are don't copied. For example if I will
write:
> d1.clear()
> which clears all two dictionaries, I will find that d2's dictionaries
are also
> empty!!!
>
> Now I'am using the quick-hack:
>
> class Distribution:
>   __gr_on_transp=dict()
>   __ostatok_m=dict()
>   ...
>   def my_copy(self):
>     d2=copy.deepcopy(self)
>     d2.__gr_on_transp=self.__gr_on_transp.copy()
>     d2.__ostatok_m=self.__ostatok_m.copy()
>     return d2
>
> It's work well, but I don't understand why previous is wrong and how
to do it
> in right way.
>
> Alexander, zatv at bk.ru


Hello, Alexander,

I just asked about deepcopy here in comp.lang.python a few weeks ago.
Here is a link to that discussion:

http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/41269228e1827a87

You have the right idea when you create a special method inside your
class to handle the deepcopy operation.  But if you call that method
__deepcopy__, then copy.deepcopy() can find it and call it.

In my code, it was also important that I declare my class as a
new-style class, so that I could use the __new__ method.  __new__
constructs a new instance of the class without initializing it.

To make your class into a new-style class, you would write "class
Distribution(object):" instead of just "class Distribution:".

There are more details in the discussion that I referenced above.  Hope
that helps!

--
Rainforest laid low.
"Wake up and smell the ozone,"
Says man with chainsaw.
John J. Ladasky Jr., Ph.D.




More information about the Python-list mailing list