Overriding "__setattr__" of a module - possible?

Michele Simionato michele.simionato at gmail.com
Tue Jun 15 23:34:47 EDT 2010


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):
   def __init__(self, dic):
       vars(self).update(dic)
   def __setattr__(self, name, value):
       print "setting %s=%s" % (name, value)
       object.__setattr__(self, name, value)

a = 1
def f():
   print 'called f'

sys.modules[__name__] = FakeModule(globals())

Here is an ipython session:

In [1]: import x

In [2]: x.a
Out[2]: 1

In [3]: x.f
Out[3]: <function f at 0x93f5614>

In [4]: x.f()
called f

In [5]: x.a=2
setting a=2

In [6]: x.a
Out[6]: 2




More information about the Python-list mailing list