How can we find all the variables in a python program??? for eg. Input
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
Output
Variables-- f,j,i
Note that the set of variable names is potentially infinite, due to setattr and some other dynamic programming techniques (such as exec). You can, however, perform simple static analysis with the ast module:
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))
Having answered a similar question before, I'll paste the relevent bits here:
For help finding things in the current namespace, check out the pprint library, the dir builtin, the locals builtin, and the globals builtin.
Please note that functions do not have any variables in existence until the actually run. See JBernardo's answer for getting to the variables within compiled functions. For example:
>>> 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']
>>>
See how the test function is located in the local namespace. I've called dir() on it to see interesting contents, and the i variable is not listed. Compare that to a class declaration and object creation:
>>> 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']
>>>
Finally, notice how this does not say if these items are variables, constants, functions, or even classes declared inside the class! Use at your own risk.
factdoesn't count as a variable? It's a mutable, untyped binding just likef,iandj. Or do you simply want to extract only the local variable names from a single given function?