tags:

views:

60

answers:

3

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?

+4  A: 
>>> getattr(__builtins__, 'range')
<built-in function range>
Duncan
Perfect! Thank you!
Wai Yip Tung
A: 

Use the __builtins__ "superglobal". It contains exactly what you're looking for

Triptych
+2  A: 

Use __builtin__ (without the s at the end like Triptych and Duncan suggest):

>>> import __builtin__
>>> getattr(__builtin__, 'range')
<built-in function range>

__builtins__ is CPython-implementation specific thus makes your code less portable.

ChristopheD
Thanks! I did't notice the fine distinction between `__builtins__` and `__builtin__`.
Wai Yip Tung