How to use dill to serialize a class definition?

前端 未结 2 1605
花落未央
花落未央 2020-12-10 03:10

In the answer to Python pickle: dealing with updated class definitions, the author of the dill package writes:

\"Ok, I have added this feature to di

2条回答
  •  情书的邮戳
    2020-12-10 04:01

    If this functionality were that important, it would be in the language core by now. :-) So, no, this is not critical to use Python in any advanced form - and if you have a project that relies on being able to re-instantiate objects based in old models - which is possible, you have to carefully think about it, and probably keep the old models around in explicit code, instead of having then serialized.

    My advice is just "leave that apart" until you think you actually need it, and had compared it with other solutions, like a strong model migration policy.

    That said, I've tried dill, and it works as advertised: it can serialize a class just like pickle can do with ordinary objects using the "dump" and "dumps" calls, and rebuild the class object with "load" and "loads".

    What probably is getting you confused is that serializing an object (through pickle or dill alike) does not include neither its source code (i.e. the actual lines of textual Python code used to define the class), nor its name.

    So, if a class is named "A", when it is serialized, if you need that name after "undilling" it, you have to reassign that name to it in the global name space. It's orignal name is preserved in it's __name__ attribute. (and for your purposes of multiple versions of the same model living together, that would lead to a lot of conflict).

    Thus:

    class A(object):
        ...
    
    import dill
    
    dill.dump(A, open("myfile", "w"))
    
    del A
    ....
    someclass = dill.load(open("myfile"))
    print (someclass.__name__)
    globals()[someclass.__name__] = someclass
    # at this point you have the "A" class back in the global namespace
    

提交回复
热议问题