getattr() in default namespace.

Carl Banks imbosol at aerojockey.com
Thu Apr 8 15:10:35 EDT 2004


python at simon.vc (SimonVC) wrote in message news:<fa156589.0404080247.6557408e at posting.google.com>...
> Hi group, long time reader first time poster (ive always wanted to say
> that).
> 
> How do you use getattr() to get a refernce to a function defined in
> the default namespace..

It's not really possible to do this in general.  I know of no way, for
example, to access the current namespace with getattr inside a class
definition.

However, I'm assuming you're taking about a module's namespace (i.e.,
a so-called global namespace) and not a class or function namespace. 
You can do this very easily with "namespace = __import__(__name__)". 
It even works at top level.


 Python 2.3.2 (#2, Dec 17 2003, 13:21:01) [C] on hp-ux11
 Type "help", "copyright", "credits" or "license" for more
information.
 >>> a = 1
 >>> namespace = __import__(__name__)
 >>> getattr(namespace,'a')
 1



-- 
CARL BANKS



More information about the Python-list mailing list