On Monday 08 September 2003 21:27, nr nr wrote:
> I'm running into problems trying pickle/unpickle instances of the follo=
> I looked at the contents of the dumped file, and see that inner class n=
> are not decorated with those of containing classes, thus it's
> understandable that unpickling fails. In fact, python docs at
> http://www.python.org/doc/current/lib/node64.html , "3.14.4 What can be
> pickled and unpickled?" state that pickleable classes are "classes that=
> defined at the top level of a module".
If you read further down that same web page the reason why you can't pick=
unpickle non-top-level functions or classes is explained:
Similarly, classes are pickled by named reference, so the same restrictio=
the unpickling environment apply. Note that none of the class's code or d=
is pickled, so in the following example the class attribute attr is not=20
restored in the unpickling environment:=20
attr =3D 'a class attr'
picklestring =3D pickle.dumps(Foo)
These restrictions are why picklable functions and classes must be defin=
the top level of a module.=20
> Surprisingly, however, the docs also say that python raises an exceptio=
> a passed-in object may not be pickled. Perhaps it doesn't apply
> pickleability-tests on contained objects?
It doesn't see them at all because classes are not pickled, only a named=20
reference to them exists, so it does not apply that test.
> Then I tried munging the pickled file to manually decorate inner-class
> names so that A1(...) read A.A1(...). Unfortunately that didn't work, =
> guess there's no namespace searching during unpickling.
No classes or class attributes are pickled, only their fully qualified na=
used as a reference from the pickled instance to the class. I'm not sure=
you want to use nested classes, I've never seen any compelling use for th=
in Python. I can understand Java programmers wanting to use them out of=20
habit, but it is a very uncommon pattern in Python.
> So short of writing my own repr-based mechanism or some such, is there =
> easy way I could use inner classes with pickle? Some incantation that,=
> a short duration, makes inner classes available at top-level scope?
Nope. Pickling classes and all of their attributes is a whole nother pro=
Although Zope is pushing some of these boundaries with persistent modules=
do not know if it handles nested classes or functions.