How to use __getattr__ to the current module, for automatically add attributes of the real-time

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Sep 18 05:26:24 EDT 2012


----- Original Message -----
> Want to work so:
> 
> import sys
> class Foo(object):
>     def __getattr__(self, t):
>        print 'use __getattr__ - ', t
>        return type(t, (object,), {})
>     def funct1(self): pass
>     def funct2(self): pass
> 
> sys.modules[__name__] = Foo()
> ttt('yy')
> 
> name 'ttt' is not defined.
>  __getattr__ not work (((.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I think __getattr__ would be triggered by using Foo().ttt or getattr(Foo(), 'ttt').

I think this hack is meant to work on modules object only, not in the global namespace where locals() and globals() are used instead (global namespace may not be the proper word, I don't know if there is a technical term for that).

Here's how to make it work:

foo.py

import sys
class Foo(object):
    def __getattr__(self, t):
       print 'use __getattr__ - ', t
       return type(t, (object,), {})
    def funct1(self): pass
    def funct2(self): pass

sys.modules[__name__] = Foo()

Now in a python shell, or in another file:

import foo
foo.ttt

use __getattr__ -  ttt
use __getattr__ -  ttt
< <class 'ttt'>

JM

PS : Looks like a hell of a hack



More information about the Python-list mailing list