Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize object from the pickle in the __init__ function

I have a class where I would like to instantiate the object in several ways depending on the arguments. When I pass a filepath to the function __init__ it should restore all parameters from the object saved as a pickle file. Is there any smart way to do so, something like self=load(...)

like image 666
freude Avatar asked Aug 17 '26 19:08

freude


2 Answers

Doing self=load(...) in your __init__ only masks the local self variable in the __init__, it does not change the instance.

You can instead control the creation of the new instance in the __new__ method of the class.

import pickle

class Pretty(object):
    def __new__(cls, filepath=None, *args, **kwargs):
        if filepath:
            with open(filepath) as f:
               inst = pickle.load(f)
            if not isinstance(inst, cls):
               raise TypeError('Unpickled object is not of type {}'.format(cls))
        else:
            inst = super(Pretty, cls).__new__(cls, *args, **kwargs)
        return inst

You can do a quick instance check of the unpickled object to ensure it is actually an instance of your class, otherwise you can expect bad behavior such as the __init__ method of your class not being called.

like image 199
Moses Koledoye Avatar answered Aug 19 '26 10:08

Moses Koledoye


As stated in another answer, self = load(...) only replaces the local variable self. The same answer recommends resorting to the __new__ method of the class which works but isn't a good practice in python, as overriding this method should be used for immutable types only.

Instead, you should be using a factory, which can in this case be a simple function :

def foo_factory(filename=None, *args, **kwargs):
    if filename:
        foo_factory.foo = pickle.load(filename)
    else:
        foo_factory.foo = Foo(*args, **kwargs)
    return foo_factory.foo

where we supposed that class Foo is the class of interest.

(see Why is __init__() always called after __new__()? for more details and references)

like image 30
rdbs Avatar answered Aug 19 '26 09:08

rdbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!