Pickling classes (not class instances)

Aaron Brady castironpi at gmail.com
Sat Feb 14 10:26:20 CET 2009

On Feb 14, 2:19 am, Nicolas M. Thiéry <Nicolas.Thi... at u-psud.fr>
>          Dear python developers,
> I got no answer to my previous post on this thread "Pickling classes
> (not class instances)".
> This issue is a show stopper for our project. Any suggestion for where
> to ask?
snip to
> > How to customize how a class (not an instance of a class!!!) is
> > pickled?
> > Is there a specific reason for this restriction?
> > Would it be thinkable to move up the copy reg dispatch before the
> > metaclass treatment in pickle and cPickle? I did it locally, and it
> > fixed my problem.
> > If not, what would be the right way to achieve this?

Hi Nicolas,

I couldn't get yours to work.  I also tried defining '__reduce__' and
'__getstate__' in the metaclass; they didn't work either.

Can you just subclass Pickler, and override the 'save' method?

> > Is there a specific reason for this restriction?

It sounds very odd.  I'm not a core dev, so I can't say.

I also tried defining '__subclasshook__' to convince 'metaclass' it is
not a subclass of 'type'.  It didn't work, but 'register' was not
working the way I wanted.

Perhaps you could define your own 'custom_type' type, which looks and
acts just like type, but just doesn't pass the 'subclass' test.  It
may be as simple as just cutting-and-pasting the TypeObject definition
from the core.

More information about the Python-list mailing list