5

Possible Duplicate:
Python: How do I pass a variable by reference?

I'm trying to write a function that modifies one of the passed parameters. Here's the current code:

def improve_guess(guess, num): 
  return (guess + (num/guess)) / 2

x = 4.0
guess = 2.0
guess = improve_guess(guess, x)

However, I want to write the code in such a way that I don't have to do the final assignment. That way, I can just call:

improve_guess(guess,x) 

and get the new value in guess.

(I intentionally didn't mention passing-by-reference because during my net-searching, I found a lot of academic discussion about the topic but no clean way of doing this. I don't really want to use globals or encapsulation in a list for this.)

Community
  • 1
  • 1
recluze
  • 1,920
  • 4
  • 21
  • 34
  • 5
    `improve_guess(3, x)` - how are you going to 'modify' the `3`? – eumiro Dec 04 '12 at 14:30
  • We usually do this in C and Java using parameter passing by reference. That way, the `guess` parameter becomes an alias for the argument that was sent in. – recluze Dec 04 '12 at 14:31
  • Oh, I see what you mean but my usecase would only deal with variables. – recluze Dec 04 '12 at 14:32
  • "We usually do this in C and Java using parameter passing by reference." What? How would you do this in Java? "That way, the guess parameter becomes an alias for the argument that was sent in." There's no such thing in C or Java. – newacct Dec 04 '12 at 21:08

2 Answers2

7

You can't do this directly since integer and floating-point types are immutable in Python.

You could wrap guess into a mutable structure of some sort (e.g. a list or a custom class), but that would get very ugly very quickly.

P.S. I personally really like the explicit nature of guess = improve_guess(guess, x) since it leaves no doubt as to what exactly is being modified. I don't even need to know anything about improve_guess() to figure that out.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

But those are the only two ways to do it: either use a global, or use a mutable type like a list. You can't modify a non-mutable variable in Python: doing so just rebinds the local name to a new value.

If you really don't like wrapping in a list, you could create your own class and pass around an instance that will be mutable, but I can't see any benefit in doing that.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • "doing so just rebinds the local name to a new value" Assignment always rebinds the variable to a new value. It has nothing to do with mutable or not mutable. "You can't modify a non-mutable variable in Python" Variables are not mutable or not mutable -- the objects that the variables point to can be. But saying you can't modify a non-mutable object is kind of a tautology. – newacct Dec 04 '12 at 21:10