Wrapping classes

Paolino paolo_veronelli at tiscali.it
Fri Sep 23 10:28:42 CEST 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?
> 
A generic approach would override __getattribute__ to let it perform the 
  __init__ method on not initialized objects.This is a case for using 
metaclasses as even __init__ method must be overridden ad hoc to 
register the arguments for the lazy initialization.
Probably you want to fine-tune the triggering (specifing which attribute 
should make it happen ),as every look up would trigger.....

class NotInitializedObjects(type):
   def __init__(cls,*_):
     realInit=cls.__init__
     def __newInit__(self,*pos,**key):
       def _init():
         realInit(self,*pos,**key)
       self._init=_init
     cls.__init__=__newInit__
     def __getattribute__(self,attr):
       def getter(attr):
         return object.__getattribute__(self,attr)
       if '_init' in getter('__dict__'):
         getter('_init')()
         del self._init
       return getter(attr)
     cls.__getattribute__=__getattribute__


if __name__=='__main__':
   class Class:
     __metaclass__=NotInitializedObjects
     def __init__(self,*pos,**key):
       self.initialized=True
       print 'initializing with',pos,key
   a=Class('arg',key='key') # a fake initialization

   try:
    object.__getattribute__(a,'initialized')
   except AttributeError: # should raise
    print 'not initialized'
   else:
    raise
   try:
    a.initialized  #every look up would do ,even a print
   except AttributeError:
    raise
   else:
    print 'initialized'


Have fun Paolino

	

	
		
___________________________________ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it



More information about the Python-list mailing list