Python | Accessing variable value from code scope
Sometimes, we just need to access a variable other than the usual way of accessing by it’s name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let’s talk about some of this functions.
Method #1 : Using locals()
This is a function that stores the values of all variables in local scope of function if in a function or of global scope if outside.
# Python3 code to demonstrate working of # Accessing variable value from code scope # using locals # initialize variable test_var = "gfg is best" # printing original variable print("The original variable : " + str(test_var)) # Accessing variable value from code scope # using locals res = locals()['test_var'] # printing result print("Variable accessed using dictionary : " + str(res)) |
The original variable : gfg is best Variable accessed using dictionary : gfg is best
Method #2 : Using globals()
This is yet another function that maintains a dictionary of variables of global scope.
# Python3 code to demonstrate working of # Accessing variable value from code scope # using globals # initialize variable test_var = "gfg is best" # printing original variable print("The original variable : " + str(test_var)) # Accessing variable value from code scope # using globals res = globals()['test_var'] # printing result print("Variable accessed using dictionary : " + str(res)) |
The original variable : gfg is best Variable accessed using dictionary : gfg is best
Recommended Posts:
- Python | Accessing Key-value in Dictionary
- Accessing Attributes and Methods in Python
- Python | Accessing index and value in list
- Python | Accessing all elements at given list of indexes
- Python | Accessing nth element from tuples in list
- Namespaces and Scope in Python
- Scope Resolution in Python | LEGB Rule
- Python | Scope resolution when a function is called or defined
- Counters in Python | Set 2 (Accessing Counters)
- Python | Variable list slicing
- __name__ (A Special variable) in Python
- Python | Check if a variable is string
- Python | Using variable outside and inside the class and method
- Print Single and Multiple variable in Python
- Python | Set 6 (Command Line and Variable Arguments)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



