Store object using Python pickle, and load it into different namespace

前端 未结 3 1989
失恋的感觉
失恋的感觉 2021-01-12 02:08

I\'d like to pass object state between two Python programs (one is my own code running standalone, one is a Pyramid view), and different namespaces. Somewhat related questio

3条回答
  •  [愿得一人]
    2021-01-12 02:54

    Use dill instead of pickle, because dill by default pickles by serializing the class definition and not by reference.

    >>> import dill
    >>> class MyClass:
    ...   def __init__(self): 
    ...     self.data = set()
    ...     self.more = dict()
    ...   def do_stuff(self):
    ...     return sorted(self.more)
    ... 
    >>> c = MyClass()
    >>> c.data.add(1)
    >>> c.data.add(2)
    >>> c.data.add(3)
    >>> c.data
    set([1, 2, 3])
    >>> c.more['1'] = 1
    >>> c.more['2'] = 2
    >>> c.more['3'] = lambda x:x
    >>> def more_stuff(self, x):  
    ...   return x+1
    ... 
    >>> c.more_stuff = more_stuff
    >>> 
    >>> with open('my_c.pik', "wb") as f:
    ...   dill.dump(c, f)
    ... 
    >>> 
    

    Shut down the session, and restart in a new session…

    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
    >>> with open('my_c.pik', "rb") as f:
    ...   c = dill.load(f)
    ... 
    >>> c.data
    set([1, 2, 3])
    >>> c.more
    {'1': 1, '3':  at 0x10473ec80>, '2': 2}
    >>> c.do_stuff()
    ['1', '2', '3']
    >>> c.more_stuff(5)
    6
    

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

提交回复
热议问题