Metaclasses vs. standard Python reflection?

Robin Becker robin at jessikat.fsnet.co.uk
Sat May 3 13:51:15 EDT 2003


.....when trying to intercept/hook instance __setattr__ magic I find it
extremely hard with mundane python. 

ie
>>> import new
>>> class A: pass
... 
>>> a=A()
>>> def hook(self,k,v):
...     print 'hook(%s,%s,%s)' % (repr(self),repr(k),repr(v))
... 
>>> a.__setattr__=new.instancemethod(hook,a,a.__class__)
>>> a.c=3
>>> a=A()
>>>

we didn't hook __setattr__

Is this something that is easily handled using some metaclass approach? 
Currently I believe I have to do something complex  ie

>>> a=A()
>>> class _HOOK:
...     def __setattr__(self,k,v):
...             print 'hook(%s,%s,%s)' % (repr(self),repr(k),repr(v))
... 
>>> a.__class__=new.classobj(a.__class__.__name__,a.__class__.__bases__+
(_HOOK,),a.__class__.__dict__)
>>> a.y=3
hook(<__main__.A instance at 0x0120F298>,'y',3)
>>>

and even this isn't quite right as a is not an instance of A (I guess we
need to put a.__class__ into the bases). 
-- 
Robin Becker




More information about the Python-list mailing list