HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Lazy class instantiation in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
instantiationlazyclasspython

Problem

I've written some class which allows me to derive from it to make objects lazy-instantiated. Do you see notational improvements or maybe even cases where this method might not work (multiple inheritance etc.)? What else could I try?

class LazyProxy(object):
    def __init__(self, cls, *params, **kwargs):
        self.__dict__["_cls"]=cls
        self.__dict__["_params"]=params
        self.__dict__["_kwargs"]=kwargs

        self.__dict__["_obj"]=None

    def __getattr__(self, name):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        return getattr(self.__dict__["_obj"], name)

    def __setattr__(self, name, value):
        if self.__dict__["_obj"] is None:
            self.__init_obj()

        setattr(self.__dict__["_obj"], name, value)

    def __init_obj(self):
        self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"])
        self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"])

class LazyInit(object):
    def __new__(cls, *params, **kwargs):
        return LazyProxy(cls, *params, **kwargs)

class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit
    def __init__(self, x):
        print("Init A")
        self.x=14+x

a=A(1)
print("Go")
print("15=", a.x)

Solution

Would be cool as a class decorator.

@Lazy
class MyFoo:
    ...


To me it seems like it would fit nicely as a class decorator because it's independent of what the class is representing. It has more to do with the way the class works internally than it does with the thing that the class embodies.

Code Snippets

@Lazy
class MyFoo:
    ...

Context

StackExchange Code Review Q#10481, answer score: 2

Revisions (0)

No revisions yet.