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

Steve Holden sholden at holdenweb.com
Thu Sep 11 09:00:01 EDT 2003


"Stephen Horne", using a ridiculous bogus email address, wrote...
> On Wed, 10 Sep 2003 16:55:28 +0200, Peter Otten <__peter__ at web.de>
> wrote:
>
> >Obviously, your example could easily be rewritten to
> >
> >def inc(p):
> >    return p + 1
> >
> >x = inc(x)
> >
> >and a similar function with two by-ref parameters would still be
readable:
> >
> >x, y  = inc2(x, y)
> >
> >So here's my question. How many functions are there in your *real* code
that
> >could benefit from, say three or more by-ref parameters?
> >Hint: for me it comes close to 0 :-)
>
> Its not an issue of whether the same effect can be achieved in Python.
> It's more an issue of whether the method used expresses the
> programmers intentions properly.
>
> If a function is defined as...
>
>   def Inc (p) :
>     return p + 1
>
> then that to me expresses an intention which is different to that
> expressed by...
>
>   def Inc (ref p) :
>     p += 1
>
> The latter case expresses the intention to in-place rebinding of the
> parameter. In doing so, it better expresses the purpose of some kinds
> of functions (though not this noddy example, obviously).
>
> This is all very fuzzy, so let's examine an example which is based on
> an issue in some real Python code (though this is simplified to make
> the point). The problem is to insert an object into some container -
> appending to a list will do here. However, the object being inserted
> will typically be quite large, so we want to avoid copying it if
> possible.
>
> No problem there, it seems...
>
>   class c_Container :
>     f_List = []
>
>     def Add (self, p_Object) :
>       f_List.append (p_Object)
>
> The problem with this, however, is the risk of accidental
> side-effects. If the caller goes on to modify the object that he
> passed as a parameter, that will change the content of the container.
>
I don't see why this is any different, or worse, than having a function
modify a single reference. You are setting your calling code up to fail due
to the invisible side-effects of the function call. This is a Bad Idea.

[...]
> >By the way, this is strictly from a user perspective, I trust the Python
> >developers to overcome the implementation issuses, *if* there is a
> >significant usability improvement.
>
> And that is the big question.
>
> C# 'needs' ref parameters because it has no convenient way to return
> multiple values from a function. Python does not. The question is
> really whether this argument about expressing intentions and evading
> errors is compelling or not.
>
You have still to convince me that there would be any gain whatsoever. Think
of me as the forces of reaction ;-)

regards
-- 
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/







More information about the Python-list mailing list