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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :



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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

The original variable : gfg is best
Variable accessed using dictionary : gfg is best


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.