var or inout parm?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Dec 7 07:17:02 EST 2008
On Sun, 07 Dec 2008 08:54:46 +0000, mh wrote:
> How can I make a "var" parm, where the called function can modify the
> value of the parameter in the caller?
By using another language.
> def f(x):
> x = x + 1
>
> n = 1
> f(n)
> # n should now be 2
Python doesn't work like that. You should read this:
http://effbot.org/zone/python-objects.htm
Some work arounds, in order from worst-to-best:
(1) Use a hard-coded global name:
x = 1
def f():
global x
x = x + 1
f()
assert x == 2
(2) Wrap the value you want to change in a list, then modify the list in
place.
n = [1]
def f(alist):
alist[0] = alist[0] + 1
f(n)
assert n[0] == 2
(4) Just use an ordinary function. Functions can return multiple values.
n = 1
def f(x):
return (x+1, 99)
n, y = f(n)
assert y == 99
assert n == 2
(5) Find another way to solve your problem.
Why do you think you need var parameters? What problem are you hoping to
solve by using them? As a former Pascal programmer, I missed var
parameters at first, but now I don't.
--
Steven
More information about the Python-list
mailing list