modifing function's parameters global value

Erik Max Francis max at alcyone.com
Tue May 13 19:14:10 EDT 2003


Federico wrote:

> Here is an example:
> 
> x=1
> def func(y):
>     y=y+1
>     print y
> print x
> func(x)
> print x # [wants this to be changed]

In Python, "assignment" is really reference rebinding, so when you
rebind the local name y (in your function), it has no effect on the
surrounding bindings.

The short answer is that you can't get this transparently; you're going
to have to do a little legwork yourself.  One way to get what you want
is to return the result in the function and use that to reassign the
variable:

	x = func(x)

Another way is to pass in a mutable container object which you can then
modify inside the functin so that it will have effects outside:

>>> q = [1]
>>> def f(x): 
...  x[0] += 1
... 
>>> q
[1]
>>> f(q)
>>> q
[2]

This can look a little like black magic, so when I find it necessary
(which I have on occasion), I prefer a wrapper class that makes it
explicit.  Say something like

	class Container:
	    def __init__(self, value=None): self.set(value)
	    def set(self, value): self.value = value
	    def get(self): return self.value

Then your code has the much more deliberate look of

	q = Container(1)
	def f(x);
	    x.set(x.get() + 1)
	f(q)
	print q.get()

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ It's a sky-blue sky / Satellites are out tonight
\__/  Laurie Anderson




More information about the Python-list mailing list