0

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
Community
  • 1
  • 1
idk
  • 1
  • 3
  • rename paramters, dont use `x`, `y` due to it's already represent global variable – gcdsss Nov 12 '20 at 02:21
  • x and y has to be the parameters of function foo, sorry forget to mention that. – idk Nov 12 '20 at 02:34
  • I mean you can rename `x`, `y` to other names, didn't mean to remove them, don't make paramters name as the same as global variable cause it will raise `SyntaxError` – gcdsss Nov 12 '20 at 02:39

2 Answers2

1

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]
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • Sorry forgot to mention that x and y has to be parameters of function foo. – idk Nov 12 '20 at 02:35
  • Then make the function return a list like `return [x,y]` after swap, then assign to variable and later get into x,y !! Man it's easy – Wasif Nov 12 '20 at 02:37
  • Sorry I am still learning. I do not get it. Can you visualize the steps for me please? – idk Nov 12 '20 at 02:49
0
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

Yash
  • 108
  • 9