Pass-by-reference : Could a C#-like approach work in Python?
Thomas Bellman
bellman at lysator.liu.se
Thu Sep 11 04:06:22 EDT 2003
Erik Max Francis <max at alcyone.com> writes:
> That isn't what I meant. Look at the following code:
> someFunction(thisArgument, thatArgument)
> With Python as it stands right now, I know that this call can never
> rebind the names thisArgument and thatArgument. It doesn't matter what
> someFunction is, it doesn't matter what thisArgument or thatArgument
> are. I know it can never happen.
> With your proposed change, now whenever I see a function call in code I
> don't know whether it's going to rebind names from the caller's side.
> It might, it might not. Furthermore, with Python's dynamicism, it might
> be hard to tell without running the code (since functions are first
> class objects, inspecting the function name may not help).
No, you *would* know. The above call would *not* be able to
rebind any of thisArgument or thatArgument. In fact, if
someFunction() is defined with a ref parameter, the call would
*fail*, raising an exception. Just like calling it with the
wrong number of parameters would.
For someFunction() to be able to rebind, e.g, thisArgument, there
are *two* prerequisites:
1. someFunction() must be defined as 'def someFunction(ref a, b)'.
2. the *call* must be 'someFunction(ref x, y)'.
*Both* these must be met. If only one of them is met, the call
will fail.
Here's a sample session of what would happen under Stephen's
model:
>>> def ref_f(ref x):
... x = 17
...
>>> def norm_f(x):
... x = 23
...
>>> a = 0
>>> ref_f(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ref_f() must have reference parameter
>>> print a
0
>>> ref_f(ref a)
>>> print a
17
>>> norm_f(a)
>>> print a
17
>>> norm_f(ref a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: norm_f() must not have reference parameter
>>> print a
17
(For the record, I do not support Stephen's proposal, nor any
other kinds of call-by-reference in Python. For one, I don't
think it meshes well with the rest of Python, and moreover, I
have yet to encounter a real-world example where this would
actually make code more readable - and I have been using Python
for eight years now, and Lisp (which has similar call semantics)
for a few years before that.)
--
Thomas Bellman, Lysator Computer Club, Linköping University, Sweden
"God is real, but Jesus is an integer." ! bellman @ lysator.liu.se
! Make Love -- Nicht Wahr!
More information about the Python-list
mailing list