__getattr__ on a module

Posted by Matt Joiner on Stack Overflow See other posts from Stack Overflow or by Matt Joiner
Published on 2010-03-15T13:20:08Z Indexed on 2010/03/15 13:29 UTC
Read the original article Hit count: 361

Filed under:
|
|
|

How can implement the equivalent of a __getattr__ on a class, on a module?

Example

When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on the module.

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

def __getattr__(mod, name):
    return getattr(A(), name)

if __name__ == "__main__":
    salutation("world")

Which gives:

matt@stanley:~/Desktop$ python getattrmod.py 
Traceback (most recent call last):
  File "getattrmod.py", line 9, in <module>
    salutation("world")
NameError: name 'salutation' is not defined

Evidently something is not right about my assumed implementation.

© Stack Overflow or respective owner

Related posts about python

Related posts about getattr-