How can I tell whether a variable in Python is global or local?
Asked
Active
Viewed 2,328 times
0
-
1Can you say more about exactly what you're doing? It's rather unusual to need to be able to tell whether a variable is local or global, and there might well be a better way to solve whatever issue you're facing. – Mark Dickinson Jan 29 '17 at 20:57
-
Well, for one, if it's not in `globals()`, then it's definitely not global. – the_constant Jan 29 '17 at 21:03
-
Hi, I need to know whether the variables are global or local because the task I'm doing requires documentation and so I need to record a number of things. I'm making a treasure hunt game and have created multiple subroutines to account for the user choosing the grid size, inputting their movements etc. In the choosing grid size subroutine, I've used a variable called 'choice' but have also used this in the main s/r to account for what choice is made at main menu. In this case, is the variable global since it is used multiple times for different processes, or local? – Ellie Jan 29 '17 at 21:06
-
@Ellie As long as you didn't used `global choice` in your function / subroutine, the local variable will be used in the function – ovs Jan 29 '17 at 21:18
-
Now you know why global variables are generally frowned upon. The easiest way to keep track if you must use them is to use a naming convention. – Mark Tolonen Jan 29 '17 at 21:21
2 Answers
3
globals() will return a dict of global variables
locals() will return a dict of local variables
to check if the scope of the variable:
if 'variable' in locals(): print("It's local") #Replace 'variable' with the variable
elif 'variable' in globals(): print("It's global") #But keep the quotation marks
else: print("It's not defined")
If you don't know about scopes, heres a good page to go to https://stackoverflow.com/a/292502/7486769
-
Hi, how do I use this exactly to check? Please bear with me because I'm only a student and don't have a great deal of complex understanding in terms of python. If I just paste this at the bottom of my code will it output the variables that are global/ local? – Ellie Jan 29 '17 at 21:12
-
2I would change the order of `var in globals()` and `var in locals()`. When a var is in `locals` and in `globals` the local variable will be used. – ovs Jan 29 '17 at 21:13
-
2
0
If all you are doing is making a list for some documentation, all you need to do is create a list of variables that are defined outside of any function or class.
var1 = "something"
def foo():
var2 = "something"
In the above, var1
is global, var2
is local.

Bryan Oakley
- 370,779
- 53
- 539
- 685