3

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

3
  • 4
    You're aware that you'll need much better-structured and fine-grained data (e.g. scoping information) to actually reason about the program? The dynamic features of Python make this impossible in general in any case though... Besides, how come fact doesn't count as a variable? It's a mutable, untyped binding just like f, i and j. Or do you simply want to extract only the local variable names from a single given function? Commented Jan 12, 2012 at 18:57
  • This is jus a sample program,,,in actual program can be of any type and of any length... All i wnt to do is find all the variables used in that python program.... Commented Jan 12, 2012 at 19:04
  • Why can't you read the source to find the assignment statements? Commented Jan 12, 2012 at 19:28

4 Answers 4

8

You can get this information from functions:

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

Note these variables names will be generated only if the bytecode for them is built.

>>> def f():
        a = 1
        if 0:
            b = 2
>>> f.func_code.co_varnames
('a',)
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

1

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.

Comments

0

globals() will return a dict of all the global variables.

locals() will return a dict of all local variables, e.g. all the variables in the scope it's called from.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.