Python: Function To Alter A Global Variable That Is Also Parameter
def fxn(L): ''' ''' global L = 2 L = 1 fxn(L) print(L) I have a function like the one above. Assume I need the function to alter the global variable from within the
Solution 1:
You should not use the same variable as global variable and the functional argument to the function using that global variable.
But since you have asked, you can do it using the globals()
and locals()
. Below is the sample code:
>>>x = 5>>>defvar_test(x):...print('GLOBAL x: ', globals()['x'])...print('LOCAL x: ', locals()['x'])...globals()['x'] = 111...print('GLOBAL x: ', globals()['x'])...print('LOCAL x: ', locals()['x'])...>>>var_test(20)
GLOBAL x: 5
LOCAL x: 20
GLOBAL x: 111
LOCAL x: 20
Solution 2:
This is a bad idea, but there are ways, for example:
a = 5deff(a):
defchange_a(value):
global a
a = value
change_a(7)
f(0)
print(a) # prints 7
In reality, there is seldom any need for writing to global variables. And then there is little chance that the global has the same name as a variable which just cannot change the name.
If you are in such a situation, ask yourself "am i using global
too often?"
Post a Comment for "Python: Function To Alter A Global Variable That Is Also Parameter"