Overriding "__setattr__" of a module - possible?
John Nagle
nagle at animats.com
Wed Jun 16 00:16:55 EDT 2010
On 6/15/2010 8:34 PM, Michele Simionato wrote:
> On Jun 16, 4:43 am, John Nagle<na... at animats.com> wrote:
>> Is it possible to override "__setattr__" of a module? I
>> want to capture changes to global variables for debug purposes.
>>
>> None of the following seem to have any effect.
>>
>> modu.__setattr__ = myfn
>>
>> setattr(modu, "__setattr__", myfn)
>>
>> delattr(modu, "__setattr__")
>>
>> John Nagle
>
> There is a dirty trick which involves fiddling with sys.modules.
> For instance:
>
> $ cat x.py
> import sys
>
> class FakeModule(object):
Cute, but it doesn't work in general. Faking a module as a
class fails when you simply call
x()
within the module.
I also tried
modu.__dict__['__setattr__'] = myfun
...
modu.foo = 1 # "myfun" does not get called.
Any more ideas?
John Nagle
More information about the Python-list
mailing list