Pass-by-reference : Could a C#-like approach work in Python?
Tim Hoffman
timh at zute.net
Wed Sep 10 10:39:23 EDT 2003
Hi Stephen
The bit I can't fathom is why you would want to do this ?
At least in the case of the simple example you give.
In your example aren't you really asking for a reference to a reference
to be passed, because in Python you always just pass a reference to an
object, in the sense that x = 1 is variable x pointing to the integer
object 1.
When you call inc function you are taking an immutable object 1 and
creating a new object which is the result of adding 1 to 1. And what you
are then asking it to rebind the variable x to point to the new int
object 2 inside the function.
Why you would want to do this is unclear. Secondly if it where a more
abstract object it would have an increment method which you could call
on the object which was passed to the function.
So again I just can't see why you want to do it.
Maybe I am missing something here
Tim
Stephen Horne wrote:
> I have in the past suggested that Python functions could use some kind
> of modifier token for parameters to indicate pass-by-reference, so
> that immutable items in particular could be modified (or more
> accurately replaced) by the function, with that modification affecting
> what the caller sees. In case I'm explaining this badly, here is how
> Python currently works...
>
>
>>>>def Inc(p) :
>
> ... p += 1
> ...
>
>>>>x = 1
>>>>Inc(x)
>>>>x
>
> 1
>
> ... and here is (roughly) what I'd like to be able to do...
>
>
>>>>def Inc(ref p) :
>
> ... p += 1
> ...
>
>>>>x = 1
>>>>Inc(x)
>>>>x
stuff removed.
> I would then be able to write...
>
>
>>>>def Inc(ref p) :
>
> ... p += 1
> ...
>
>>>>x = 1
>>>>Inc(ref x)
>>>>x
>
> 2
>
> Obviously the implementation would not be trivial, but i think this
> would be a very useful feature.
>
> Any thoughts?
>
More information about the Python-list
mailing list