deepcopy alternative?

Gabriel Genellina gagsl-py at
Tue Jan 30 05:54:53 CET 2007

En Mon, 29 Jan 2007 20:17:11 -0300, <"none <"> escribió:

> I have a very complex data structure which is basically a class object
> containing (sometimes many) other class objects,

What are "class objects"? instances of a given class, or a class itself?

> function references,
> ints, floats, etc.  The man for the copy module states pretty clearly
> that it will not copy methods or functions. I've looked around for a
> while (prob just using the wrong keywords) and haven't found a good
> solution.  As a workaround I've been using cPickle, loads(dumps(obj))
> which is incredibly slow (~8 sec for a 1000 elem list).
> I believe the only thing stopping me from doing a deepcopy is the
> function references, but I'm not sure.  If so is there any way to
> transform a string into a function reference(w/o eval or exec)?

What do you mean by "function reference"? A module-level function works  
fine both with pickle and copy. Methods do not; but it's not common to  
take methods out of a class and put them inside a tuple, by example...

> Example
> from copy import deepcopy
> a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj[funcRef])
> b = deepcopy(a)
> TypeError: function() takes at least 2 arguments (0 given)

Please provide a *running* example. I've added some definitions, corrected  
some syntax errors, and this full example works for me:

--- cut ---
 from copy import deepcopy

class ClassObj(object):
   def __init__(self, args): = args

def funcRef(x):
     print x

a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj([funcRef])])
b = deepcopy(a)
print a is b'hello')
print len(, len(
--- cut ---

> PS: If the answer to this is in __getstate__() or __setstate__() is
> there some reference to how these should be implemented besides the
> library reference?

Until you provide more info on your problem it's hard to tell.

Gabriel Genellina

More information about the Python-list mailing list