Python pickling after changing a module's directory

前端 未结 5 1815
生来不讨喜
生来不讨喜 2020-11-30 00:22

I\'ve recently changed my program\'s directory layout: before, I had all my modules inside the \"main\" folder. Now, I\'ve moved them into a directory named after the progra

5条回答
  •  悲哀的现实
    2020-11-30 00:56

    pickle serializes classes by reference, so if you change were the class lives, it will not unpickle because the class will not be found. If you use dill instead of pickle, then you can serialize classes by reference or directly (by directly serializing the class instead of it's import path). You simulate this pretty easily by just changing the class definition after a dump and before a load.

    Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
    [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dill
    >>> 
    >>> class Foo(object):
    ...   def bar(self):
    ...     return 5
    ... 
    >>> f = Foo()
    >>> 
    >>> _f = dill.dumps(f)
    >>> 
    >>> class Foo(object):
    ...   def bar(self, x):
    ...     return x
    ... 
    >>> g = Foo()
    >>> f_ = dill.loads(_f)
    >>> f_.bar()
    5
    >>> g.bar(4)
    4
    

提交回复
热议问题