Reputation: 21
I work a lot with a lot of global variables in Python which value constantly need to be changed when my code progresses. A very fine solution for me would be to take a global variable as an argument inside a function, however, as far as my knowledge reaches, it is only possible to change a global variable inside a function by actually naming that specific variable during the function definition. Because I work with a lot of different variablenames, this would force me to make a lot of functions per variablename.
What I want is something like this:
x = 5
def foo(_):
global _
_ = 10
return _
foo(x)
print(x)
where x now would be 10 instead of the actual output, which is 5. What is the most efficient way to reach what I want?
Upvotes: 0
Views: 413
Reputation: 1942
I may not have completely understood your need to do this, but, you can also manage globals as follows:
x = globals()
x['cartoon'] = 'mickey'
print(x['cartoon'])
Upvotes: 0
Reputation: 39404
Since you go to the trouble of naming x
when you call foo(x)
, its not too much of a stretch to do x = foo(x)
:
x = 5
def foo(_):
_ = 10
return _
x = foo(x)
print(x)
Upvotes: 1