0

How can I make a python function act on the original object that is given as an argument,

def f(x):
    x = None

y = 1
f(y)
y  # Returns 1, I want y to return None

I know that y == 1 is the correct behaviour. My question is: is there a trick that makes it possible to have a python function behave as if the argument were passed by reference?

Quant Metropolis
  • 2,602
  • 2
  • 17
  • 16

2 Answers2

1
def f(x):
    return None

y = 1
y = f(y)
y  # Returns 1, I want y to return None

You need to return from a function and assign the return to a variable

gkusner
  • 1,244
  • 1
  • 11
  • 14
0

Your function f(x) doesn't actually return anything. When you set x = None, all you're doing is reassigning the local x that's inside f; you're not actually changing the variable that you passed in. That's not something you can do very easily in Python, and you usually don't want to. You'd want something like:

def f(x):
  x = None
  return x

And then assign y to f(x) in your main code.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42