Pass-by-reference : Could a C#-like approach work in Python?

Greg Ewing (using news.cis.dfn.de) g2h5dqi002 at sneakemail.com
Tue Sep 23 00:52:41 EDT 2003


Michael Chermside wrote:
> But my counter argument would be that this breaks one of the elegent
> simplicities of Python -- that callables of all kinds are equivalent
> and have a very simple interface. ... There's no place in this simple
> protocol for type declarations (of course), and there would be no
> place for tracking whether an argument was "ref" or not.

Apologies for reviving this thread, but I'd just like to
point out how this proposal ("ref" parameters, for anyone
who's forgotten) could be implemented without adding any
complication to the argument passing model. In fact, it
could be decoupled from argument passing almost completely.

Suppose there were an expression

    ref x

which would return what I will call a Namespace Reference
Object (NRO) which refers to the binding of the name 'x'
in the current scope. It would have some suitable protocol,
such as get() and set() methods, for accessing this binding.
Note that this would be a general expression, usable anywhere,
not just in a function call.

Thats' really all that is strictly needed, because we can
now write

    def Inc(xref):
       xref.set(xref.get() + 1)

and call it with

    Inc(ref a)

However, as a convenience, we might want to allow the 'ref'
keyword to be usable on the left hand side of an expression
as well, in a kind of "unpacking" sense, so that

    ref x = xref
    x = y

would be equivalent to

    xref.set(y)

(The semantics of this are perhaps a bit murky, but would
be something line "assign xref to x, and have the
compiler note that any other mention of x in this scope
is to use the NRO protocol implicitly".)

Now we can write

    def Inc(xref):
       ref x = xref
       x += 1

Further, analogous to the way tuples can be implicitly
unpacked in an argument list, we should similarly allow
arguments to be implicitly "unrefed" in an argument list:

    def Inc(ref x):
       x += 1

This is identical to the original proposal, but is implemented
using mechanisms which are completely orthogonal to argument
passing, and could be used in other contexts if desired.

Not that I'm necessarily advocating the proposal -- I tend
to agree that there's no pressing need for passing arguments
by reference in Python. I'm just setting down these ideas
for posterity.

Okay, you can let this thread die properly now. :-)

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list