I can “pickle local objects” if I use a derived class?

后端 未结 4 1617

The pickle reference states that the set of objects which can be pickled is rather limited. Indeed, I have a function which returns a dinamically-generated clas

4条回答
  •  [愿得一人]
    2020-12-05 03:06

    I disagree, you can pickle both. You just need to use a better serializer, like dill. dill (by default) pickles classes by saving the class definition instead of pickling by reference, so it won't fail your first case. You can even use dill to get the source code, if you like.

    >>> import dill as pickle
    >>> def f():
    ...   class A: pass
    ...   return A
    ... 
    >>> localA = f()
    >>> la = localA()
    >>> 
    >>> _la = pickle.dumps(la)
    >>> la_ = pickle.loads(_la)
    >>>    
    >>> class DerivedA(localA): pass
    ... 
    >>> da = DerivedA()
    >>> _da = pickle.dumps(da)
    >>> da_ = pickle.loads(_da)
    >>> 
    >>> print(pickle.source.getsource(la_.__class__))
      class A: pass
    
    >>> 
    

提交回复
热议问题