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

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$
Wed Sep 10 20:04:44 CEST 2003

On Wed, 10 Sep 2003 15:46:11 +0000 (UTC), JCM
<joshway_without_spam at> wrote:

>Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$> wrote:
>>>>> def Inc(ref p) :
>> ...   p += 1
>> ...
>>>>> x = 1
>>>>> Inc(x)
>>>>> x
>> 2
>While I'd not be against some sort of reference-passing mechanism in
>Python, I think this is the wrong way to go--modifiability should be
>evident to the caller.

1.  I pointed out that this is an advantage of the C# system, which I
    was proposing to imitate.

: The C# solution uses a modifier keyword, but that keyword must be
: specified in both the function definition *and* the call. For
: instance...


: The rationale for this in C#, I assume, is mostly about clarity and
: maintainability - the caller can't be surprised when value type
: parameters are changed in a function as he had to explicitly allow it.

2.  You quoted the example I labelled as "(roughly) what I'd like to
    be able to do" and ignored the one where I adopted the C#

: >>> def Inc(ref p) :
: ...   p += 1
: ...
: >>> x = 1
: >>> Inc(ref x)
: >>> x
: 2

So your criticism is invalid simply because the whole point of my post
was to suggest a scheme where "modifiability should be evident to the

>  Currently, if you see a call to f(x) you know
>that x cannot be rebound.

And if in some future version of Python the suggestion I made was
implemented, when you see f(x) you will still know that x cannot be
rebound - but when you see f(ref x) you will know that x may well be

>  I'd be more in favor of something like:
>  >>> def Inc(ref p):
>  ...    p += 1
>  ... 
>  >>> x = 1
>  >>> Inc(x)
>  >>> x
>  1
>  >>> Inc(ref x)
>  >>> x
>  2

I wouldn't want this. To implement it, either a single compiled
version of a function would need to figure out at run time whether the
parameters where by reference or not, or several versions of each
function would have to be compiled into the .pyc file.

Also, I don't really see the benefit. If a function has by-reference
parameters then rebinding those parameters is likely a big part of the
purpose of the function. Supplying a parameter which cannot be rebound
is likely an error caused by someone forgetting to type the 'ref', in
which case they'd equally likely appreciate an error message as
opposed to wierd, hard-to-trace logic errors.

More information about the Python-list mailing list