3
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

I think the only real potential interaction with weirdness would be if you tried to define a __new__ on a subclass; you'd just have to take some care not to do things that your lazy instantiation code wouldn't like.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Possibly. What would be differences? In particular inheritance? Since I will actually add some class functionality to LazyInit, I decided to go with the above solution to have "all-in-one" \$\endgroup\$ – Gerenuk Mar 30 '12 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.