简体   繁体   中英

Best way to change value of global value inside a function in Python?

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?

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)

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM