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 these 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
Method #3: Using a class
- Define a class MyClass with a class-level variable my_var set to the desired value.
- Define a function func2 that prints the value of MyClass.my_var.
- Call func2 to print the value of MyClass.my_var.
class MyClass:
my_var = 'gfg is best'
def func2():
print (MyClass.my_var)
func2() # Output: gfg is best
|
gfg is best
Time complexity: O(1)
Auxiliary Space: O(1)
Method 4: using the built-in function vars().
Steps:
- Initialize a variable test_var with a string value.
- Print the original variable using the print() function.
- Use the vars() function to access the variable value from code scope and assign it to a new variable res.
- Print the result.
# initialize variable test_var = "gfg is best"
# printing original variable print ( "The original variable : " + str (test_var))
# Accessing variable value from code scope # using vars res = vars ()[ 'test_var' ]
# printing result print ( "Variable accessed using dictionary : " + str (res))
|
The original variable : gfg is best Variable accessed using dictionary : gfg is best
Time complexity of this program is O(1)
Auxiliary space required is O(1).