Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Accessing variable value from code scope

  • Last Updated : 29 Oct, 2019

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




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




# 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))
Output :
The original variable : gfg is best
Variable accessed using dictionary : gfg is best



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!