How can I lookup an attribute in any scope by name?

Posted by Wai Yip Tung on Stack Overflow See other posts from Stack Overflow or by Wai Yip Tung
Published on 2010-05-17T16:44:52Z Indexed on 2010/05/17 16:50 UTC
Read the original article Hit count: 290

Filed under:

How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g.

>>> def foo(name):
...   a=1
...   print globals().get(name), locals().get(name)
...
>>> foo('a')
None 1
>>> b=1
>>> foo('b')
1 None
>>> foo('foo')
<function foo at 0x014744B0> None

So far so good. However it fails to lookup any built-in names.

>>> range
<built-in function range>
>>> foo('range')
None None

>>> int
<type 'int'>
>>> foo('int')
None None

Any idea on how to lookup built-in attributes?

© Stack Overflow or respective owner

Related posts about python