user9362405
user9362405

Reputation:

Python: Change a global variable, which comes from a function parameter

Is there any way to have a parameter of a function, which is a global variable and in the function itself you change the value of this variable. This way you have a global variable as a parameter of a function. In the function itself you change the value of this global variable. So for example:

x = 2
a = 5
def minus_one(x):
    x -= 1 #take the global x
minus_one(x)
print(x) #Should print 1
minus_one(a)
print(a) #Should print 4

Upvotes: 2

Views: 55

Answers (1)

Olivier Melançon
Olivier Melançon

Reputation: 22294

Yes, you can do something similar.

x = 2

def minus_one(var_name):
    globals()[var_name] -= 1 # This accesses the global dict

minus_one('x') # Note that you must pass the variable name as string here

print(x) # Prints 1

Although, this is not recommended at all.

  • This can cause bugs that are extremely hard to find.

  • There is almost always a better way to do it

  • It's kind of ugly

In general, knowing the global dict exists is good. Knowing you should not use it is better.

Upvotes: 2

Related Questions