Persist a class (not an instance)
Kent Johnson
kent37 at tds.net
Fri Nov 25 08:55:28 EST 2005
Is there a way to persist a class definition (not a class instance, the actual class) so it can be restored later? A naive approach using pickle doesn't work:
>>> import pickle
>>> class Foo(object):
... def show(self):
... print "I'm a Foo"
...
>>> p = pickle.dumps(Foo)
>>> p
'c__main__\nFoo\np0\n.'
Hmm, doesn't look too promising. In a new interpreter:
>>> import pickle
>>> p='c__main__\nFoo\np0\n.'
>>> Foo = pickle.loads(p)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\lib\pickle.py", line 1394, in loads
return Unpickler(file).load()
File "C:\Python24\lib\pickle.py", line 872, in load
dispatch[key](self)
File "C:\Python24\lib\pickle.py", line 1104, in load_global
klass = self.find_class(module, name)
File "C:\Python24\lib\pickle.py", line 1140, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Foo'
The idea is to persist classes that are created and modified at runtime.
Thanks,
Kent
More information about the Python-list
mailing list