Skip to content

Instantly share code, notes, and snippets.

@llllllllll
Created February 1, 2017 19:40
Show Gist options
  • Save llllllllll/f14007ecbad07c66a43c101ca21085a2 to your computer and use it in GitHub Desktop.
Save llllllllll/f14007ecbad07c66a43c101ca21085a2 to your computer and use it in GitHub Desktop.
"""Example
.. code-block:: python
In [1]: a = Expensive(1, b=2)
In [2]: type(a)
Out[2]: __main__.LazyProxy
In [3]: a.method(3)
Out[3]: 6
In [4]: type(a)
Out[4]: __main__.Expensive
"""
class LazyProxy:
def __init__(self, type_, *args, **kwargs):
self._type = type_
self._args = args
self._kwargs = kwargs
def __getattr__(self, attr):
type_ = self._type
del self._type
args = self._args
del self._args
kwargs = self._kwargs
del self._kwargs
self.__class__ = type_
type_.__init__(self, *args, **kwargs)
return getattr(self, attr)
class Expensive:
__new__ = LazyProxy
def __init__(self, a, b):
self._expensive_thing = a + b
def method(self, arg):
return self._expensive_thing + arg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment