pickling instances of metaclass generated classes

Ian Kelly ian.g.kelly at gmail.com
Tue Jan 3 13:04:52 EST 2012


> Ok,
>
> After reading all posts (thanks a lot), I am considering to use the
> following base metaclass for all metaclasses that must lead to
> pickleable instances (not pickleable classes):
>
>
> import sys
>
> class Meta(type):
>    def __new__(mcls, name, bases, attrs):
>        cls = type.__new__(mcls, name, bases, attrs)
>        setattr(sys.modules[__name__], name, cls)
>        return cls
>
>
> if __name__ == '__main__':
>    instance = Meta("Klass", (str,),{})("apple")
>    s = pickle.dumps(instance)
>    delattr(sys.modules[__name__], "Klass")
>    Meta("Klass", (str,),{})
>    inst = pickle.loads(s)
>    print instance
>    print inst
>    print type(instance) is type(inst)
>
> Can anyone see any drawbacks to this approach? I've also tested the
> case where the Meta metaclass is defined in another module.

With this approach you'll need to be conscious of what names you allow for
classes. If you create any classes named "Meta" or "sys", or that shadow
any of the builtins, things could break. For that reason I think the
__reduce__ approach is cleaner (plus it works with the pickle system
instead of trying to fool it, so it may be more robust ib the long term),
but it's your project.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120103/77a0fb3a/attachment.html>


More information about the Python-list mailing list