Reputation: 11
For example:
x = {'a':1, 'b':2}
y = {}
# only requirement: x and y has to be parameters of function foo
def foo(x,y):
'''
How do I switch the two variables inside this function without scope issues?
'''
print('x =', x)
print('y =', y)
Result:
x = {}
y = {'a':1, 'b':2}
I tried putting global x, y
and putting x,y = y,x
inside the function but got this error as expected because they are already global:
SyntaxError: name 'x' is parameter and global
# Same thing happens for y
Upvotes: 1
Views: 1570
Reputation: 15470
If you are working with global variables, don't take args ;-)
def foo():
global x,y
x,y = y,x
Enlightening on my alternate idea
def foo(x,y):
return [y,x]
myList = foo(x,y)
x,y = myList[0], myList[1]
Upvotes: 1
Reputation: 108
x = {'a':1, 'b':2}
y = {}
def foo():
global x,y #bring global variable in func scope
x,y = y,x #swaps variable variable values
def foo1():
globals()['x'] = {'a':1, 'b':2} #update value of global variable in func
globals()['y'] = {}
#method1
foo()
print(x,y)
#method2
x = {'a':1, 'b':2}
y = {}
foo1()
print(x,y)
Both functions will work.
If you want to send the variable as args: check Pythons concept of mutability of variables. Additionally check this
Upvotes: 0