Wrapping classes

Peter Hansen peter at engcorp.com
Thu Sep 22 16:51:14 EDT 2005


Jeremy Sanders wrote:
> Is it possible to implement some sort of "lazy" creation of objects only
> when the object is used, but behaving in the same way as the object?
> 
> For instance:
> 
> class Foo:
>   def __init__(self, val):
>     """This is really slow."""
>     self.num = val
> 
> # this doesn't call Foo.__init__ yet
> a = lazyclass(Foo, 6)
> 
> # Foo is only initalised here
> print a.num
> 
> What I really want to do is make an object which looks like a numarray,
> but only computes its contents the first time it is used.

Almost anything is possible in Python, though whether the underlying 
design idea is sound is a completely different question.  (Translation: 
try the following pseudo-code, but I have my suspicions about whether 
what you're doing is a good idea. :-) )

class lazyclass(object):
     '''should probably be called lazyobject though...'''
     def __init__(self, class_, *args, **kwargs):
         self.class_ = class_
         self.args = args
         self.kwargs = kwargs
         self.obj = None

     def _getnum(self):
         if self.obj is None:
             self.obj = self.class_(*args, **kwargs)
         return self.obj.num
     num = property(_getnum)

Now that "should" do precisely what you've asked for above, though it is 
obviously very limited in supporting only a single attribute name even 
though the __init__ method is somewhat generalized.  I didn't try 
testing the code so there could be typos.

-Peter



More information about the Python-list mailing list