Saving an Object (Data persistence)

前端 未结 4 1049
你的背包
你的背包 2020-11-21 23:54

I\'ve created an object like this:

company1.name = \'banana\' 
company1.value = 40

I would like to save this object. How can I do that?

4条回答
  •  情深已故
    2020-11-22 00:02

    You can use anycache to do the job for you. It considers all the details:

    • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
    • It stores different objects to different files and reloads them properly.
    • Limits cache size
    • Allows cache clearing
    • Allows sharing of objects between multiple runs
    • Allows respect of input files which influence the result

    Assuming you have a function myfunc which creates the instance:

    from anycache import anycache
    
    class Company(object):
        def __init__(self, name, value):
            self.name = name
            self.value = value
    
    @anycache(cachedir='/path/to/your/cache')    
    def myfunc(name, value)
        return Company(name, value)
    

    Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

    For any further details see the documentation

提交回复
热议问题