By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

problem pickling objects created with the type function

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
On 21 Apr 2004 14:57:17 -0700, da***********@yahoo.com (danny) wrote:
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".

---
Greg Chapman

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.