problem pickling objects created with the type function

D

danny

Howdy,

I've run into a problem pickling objects created with a type
statement. Here's the code:

*********************************************
import pickle

class foo(object):
def __init__(self):
self.wombat = []

def setWombat(self):
self.wombat = [1]

# pickle a foo instance
x = foo()
print pickle.dumps(x) # works

# pickle a foobar instance
childType = type('foobar',(foo,),{'slor':7})
y = childType()
print pickle.dumps(y) # raises an exception
*********************************************

I'm pretty sure the failure is because 'foobar' is never in the global
namespace. If I change the code to foobar = type('foobar',... then
the code works, but I dont' want to do this because I create the class
name in a factory and it is mangled to prevent different invocations
of the factory from having the same class name.

Does anyone know how to get around this, or how to get 'foobar' =
childType into the global namespace?

thanks,
Danny
 
J

Jeff Epler

Yep.

Pickle stores instances by pickling information about the instance, plus
a string it uses to find the class.

If you do something too clever, like you did above, it doesn't work.

Jeff
 
G

Greg Chapman

I'm pretty sure the failure is because 'foobar' is never in the global
namespace. If I change the code to foobar = type('foobar',... then
the code works, but I dont' want to do this because I create the class
name in a factory and it is mangled to prevent different invocations
of the factory from having the same class name.

Does anyone know how to get around this, or how to get 'foobar' =
childType into the global namespace?

You should be able to make foobars pickleable without introducing foobar into
the global namespace by using a __reduce__ method, see:

http://www.python.org/peps/pep-0307.html

expecially the section "Extended __reduce__ API".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,829
Latest member
PIXThurman

Latest Threads

Top