Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all variables used in a python script

Tags:

python-2.7

I have a long python script which I would like to partly export to smaller scripts. Is there a way to gather all variables which are used in the specific part of the script? I don't want to define all the variables that are not used for the script. Example:

var1 = "folder"
var2 = "something else"
var3 = "another thing"

#part of the script I would like to use seperatly
dosomething(var1,var2)
#end of the part

dosomethingelse(var3)

Is there a way to list var1 and var2 as a part of my script, but not var3 as I won't need it for my new subset script?

like image 562
Alex Avatar asked Mar 01 '17 11:03

Alex


1 Answers

You can use the locals() function to determine what variables have been declared in the namespace.. ie

a = 1
b = 2
print(locals().keys())
c = 3
d = 4
print(locals().keys())

Output

['a', 'b', 'builtins', 'file', 'package', 'name', 'doc']

['a', 'c', 'b', 'd', 'builtins', 'file', 'package', 'name', 'doc']

like image 94
user2682863 Avatar answered Oct 13 '22 20:10

user2682863