How can I find an attribute in any area by name?

How can I find an attribute in any area by name? My first test is to use globals () and locals (). eg.

>>> 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, you cannot find 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 look for inline attributes?

+4
source share
3 answers
 >>> getattr(__builtins__, 'range') <built-in function range> 
+4
source

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

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

__builtins__ specific CPython implementation makes your code less portable.

+2
source

Use __builtins__ superglobal. It contains exactly what you are looking for.

0
source

Source: https://habr.com/ru/post/1310017/


All Articles