how to copy a Python object

aurelien.campeas at free.fr aurelien.campeas at free.fr
Tue Feb 7 05:29:09 EST 2006


mitsura at skynet.be a écrit :

> Hi,
>
> I am new to Python and OO programming.
> I need to copy a Python object (of a class I made myself).
> new_obj = old_object doesn't seem to work since apparently new_obj is
> then a referrence to old_obj.

it is

>
> I found out that there is a module called 'copy' that allows you to do
> a shallow or a deep copy.
> I need a deep copy since my object contains dicts to other objects that
> also need to be copied.

yes but ...

>
> However, when I do new_object = copy.deepcopy(old_object) I get a
> series of errors. The most important one:
> "
> TypeError: object.__new__(PySwigObject) is not safe, use
> PySwigObject.__new__()
> "

you see ?
that illustrates there is no general solution to the deep copy problem

>
> So any help much appreciated.

just provide your own copy() operator on your class
you and only you can know how deep you want to copy things (it just
depends on the nature of said things)

> 
> With kind regards,
> 
> Kris
> 
> I am using Python 2.4




More information about the Python-list mailing list