Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29419

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

Date 2012-09-18 11:26 +0200
From Jean-Michel Pichavant <jeanmichel@sequans.com>
Subject Re: How to use __getattr__ to the current module, for automatically add attributes of the real-time
Newsgroups comp.lang.python
Message-ID <mailman.865.1347960389.27098.python-list@python.org> (permalink)

Show all headers | View raw


----- 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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How to use __getattr__ to the current module, for automatically add attributes of the real-time Jean-Michel Pichavant <jeanmichel@sequans.com> - 2012-09-18 11:26 +0200

csiph-web