__getattr__ equivalent for a module

Leif K-Brooks eurleif at ecritters.biz
Mon Jan 15 11:28:06 EST 2007


Maksim Kasimov wrote:
> so my question is: how to tune up a module get default attribute if we 
> try to get access to not actually exists attribute of a module?

You could wrap it in an object, but that's a bit of a hack.

import sys

class Foo(object):
     def __init__(self, wrapped):
         self.wrapped = wrapped

     def __getattr__(self, name):
         try:
             return getattr(self.wrapped, name)
         except AttributeError:
             return 'default'

sys.modules[__name__] = Foo(sys.modules[__name__])



More information about the Python-list mailing list