LazyProxy in Python
Paths of destiny lead mysterious ways. Not so long ago, I was a hard-core C hacker and now, I spend a lot of the time coding in Python.
In somehow related news, I have discovered that my search-foo is not good enough, when I was unable to find a decent implementations of several design patterns in Python.
What I needed was a generic proxy that would defer initialisation of an object to the moment it is first used. Here is what I came up with:
class LazyProxy(object):
def __init__(self, cls, *args, **kw):
object.__setattr__(self, '_LazyProxy__data', (cls, args, kw))
def __get(self):
if len(self.__data) == 3:
cls, args, kw = self.__data
object.__setattr__(self, '_LazyProxy__data', (cls(*args, **kw),))
return self.__data[0]
def __getattr__(self, name):
return getattr(self.__get(), name)
def __setattr__(self, name, value):
return setattr(self.__get(), name, value)
def __delattr__(self, name):
return delattr(self.__get(), name)