python程序中使用的变量列表

时间:2012-01-12 18:54:38

标签: python variables

我们怎样才能找到python程序中的所有变量? 例如。 的输入

def fact(i):
    f=2
    for j in range(2,i+1):
        f = f * i
        i = i - 1
    print 'The factorial of ',j,' is ',f

输出

变量 - f,j,i

4 个答案:

答案 0 :(得分:8)

您可以从函数中获取此信息:

>>> fact.func_code.co_varnames
('i', 'f', 'j')

请注意,只有在构建了它们的字节码时才会生成这些变量名称。

>>> def f():
        a = 1
        if 0:
            b = 2
>>> f.func_code.co_varnames
('a',)

答案 1 :(得分:1)

请注意,由于setattr和其他一些动态编程技术(例如exec),变量名称集可能是无限的。但是,您可以使用ast模块执行简单的静态分析:

import ast

prog = ("\ndef fact(i):\n    f=2\n    for j in range(2,i+1):\n        f = f*i\n"+
       "        i = i - 1\n    print 'The factorial of ',j,' is ',f")
res = set()
for anode in ast.walk(ast.parse(prog)):
    if type(anode).__name__ == 'Assign':
        res.update(t.id for t in anode.targets if type(t).__name__ == 'Name')
    elif type(anode).__name__ == 'For':
        if type(anode.target).__name__ == 'Name':
            res.add(anode.target.id)
print('All assignments: ' + str(res))

答案 2 :(得分:1)

之前回复了similar question,我会在这里粘贴相关内容:

  

要查找当前命名空间中的内容,请查看   pprint librarythe dir builtinthe locals builtin,   and the globals builtin

请注意,在实际运行之前,函数没有任何变量。请参阅JBernardo关于获取编译函数中变量的答案。例如:

>>> def test():
...     i = 5
...
>>> locals()
{'argparse': <module 'argparse' from 'c:\python27\lib\argparse.pyc'>, '__builtins__': <module '
__builtin__' (built-in)>, '__package__': None, 'i': 5, 'test': <function test at 0x02C929F0>, '
__name__': '__main__', '__doc__': None}
>>> dir(test)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__',
 '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__',
 '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'fu
nc_dict', 'func_doc', 'func_globals', 'func_name']
>>>

查看测试函数在本地名称空间中的位置。我在其上调用dir()以查看有趣的内容,并且未列出i变量。将其与类声明和对象创建进行比较:

>>> class test():
...     def __init__(self):
...          self.i = 5
...
>>> s = test()
>>> locals()
{'argparse': <module 'argparse' from 'c:\python27\lib\argparse.pyc'>, '__builtins__': <module '
__builtin__' (built-in)>, '__package__': None, 'i': 5, 's': <__main__.test instance at 0x02CE45
08>, 'test': <class __main__.test at 0x02C86F48>, '__name__': '__main__', '__doc__': None}
>>> dir(s)
['__doc__', '__init__', '__module__', 'i']
>>>

最后,请注意这不是说这些项是变量,常量,函数,还是在类中声明的类!使用风险自负。

答案 3 :(得分:0)

globals()将返回所有全局变量的字典。

locals()将返回所有局部变量的字典,例如调用范围内的所有变量。