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


Groups > comp.lang.python > #29419 > unrolled thread

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

Started byJean-Michel Pichavant <jeanmichel@sequans.com>
First post2012-09-18 11:26 +0200
Last post2012-09-18 11:26 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  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

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

FromJean-Michel Pichavant <jeanmichel@sequans.com>
Date2012-09-18 11:26 +0200
SubjectRe: How to use __getattr__ to the current module, for automatically add attributes of the real-time
Message-ID<mailman.865.1347960389.27098.python-list@python.org>
----- 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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web