[Twisted-Python] Nested objects in pickle (was: Large projec t (IMS) architecture)

Patrick K. O'Brien pobrien at orbtech.com
Sat Jan 18 14:59:58 EST 2003

On Thursday 16 January 2003 01:09 pm, Rick Richardson wrote:
> The has-a nested relationships seem to work. Is it the is-a that is
> broken in pickle? I never knew that to be a nested relationship.

Not quite. The real issue concerns classes and functions defined within 
other classes, functions, or methods. Pickling only works on objects 
defined at the "top" level of a module. Here is an example:

>>> import pickle
>>> class Foo:
...     def __init__(self):
...         class Bar:
...             def __init__(self):
...                 self.type = 'Nested class'           
...         self.bar = Bar()
>>> foo = Foo()
>>> foo.bar.type
'Nested class'
>>> s = pickle.dumps(foo)
>>> foo2 = pickle.loads(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/local/lib/python2.2/pickle.py", line 986, in loads
    return Unpickler(file).load()
  File "/usr/local/lib/python2.2/pickle.py", line 597, in load
  File "/usr/local/lib/python2.2/pickle.py", line 767, in load_inst
    klass = self.find_class(module, name)
  File "/usr/local/lib/python2.2/pickle.py", line 824, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Bar'

For more pickling details see my article at 
http://www-106.ibm.com/developerworks/library/l-pypers.html as well as the 
section of the Python documentation dealing with Pickling limitations at 

Patrick K. O'Brien
Orbtech      http://www.orbtech.com/web/pobrien
"Your source for Python programming expertise."

More information about the Twisted-Python mailing list