开发者

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

How can I lookup an attribute in any scope by name? My first tria开发者_StackOverflow社区l 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?


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜