How can I pickle a dynamically created nested class in python?

前端 未结 6 1622
醉酒成梦
醉酒成梦 2020-11-28 05:25

I have a nested class:

class WidgetType(object):
    
    class FloatType(object):
        pass
    
    class TextType(object):
        pass

.. and

6条回答
  •  半阙折子戏
    2020-11-28 05:39

    If you use dill instead of pickle, it works.

    >>> import dill
    >>> 
    >>> class WidgetType(object):
    ...   class FloatType(object):
    ...     pass
    ...   class TextType(object):
    ...     pass
    ... 
    >>> class ObjectToPickle(object):
    ...   def __init__(self):
    ...     self.type = WidgetType.TextType
    ... 
    >>> x = ObjectToPickle()
    >>> 
    >>> _x = dill.dumps(x)
    >>> x_ = dill.loads(_x)
    >>> x_
    <__main__.ObjectToPickle object at 0x10b20a250>
    >>> x_.type
    
    

    Get dill here: https://github.com/uqfoundation/dill

提交回复
热议问题