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

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Wed Sep 10 20:21:03 EDT 2003


On Thu, 11 Sep 2003 00:50:29 +0200, Peter Otten <__peter__ at web.de>
wrote:

>Stephen Horne wrote:
>
>> However, it would probably catch a very substantial portion of real
>> accidental side-effect errors.
>
>It may be a matter of taste, but I think it will cause a *very* substantial
>portion of side effect errors. A simple example:
>
>def nested(ref o):
>    o = ReadOnly(o)
>
>def fun(o):
>    nested(ref o)
>    # so glad we can do no harm to o...riginal
>
>x = C()
>fun(x)
>x.attr = newValue # oops

I think theres a little error here (or you're interpreting the ref
differently to me). Basically...

>def fun(o):
>    nested(ref o)
>    # so glad we can do no harm to o...riginal

At this point, the parameter 'o' has been rebound to the read only
proxy so no changes can be made to it after this point in the
function, but...

>x = C()
>fun(x)

'fun' isn't using a 'ref' parameter, so 'x' is not being rebound to
the read only proxy. Therefore...

>x.attr = newValue

this will still run, and will still have the accidental side-effect.


>To go back to your container example, if copying is costly and only
>sometimes necessary, wrap the item into a copy-on-write proxy for every
>logically distinct but physically identical instance. That decision should
>be explicit rather than hidden as a side effect of a container class.

Maybe, though as you may notice in my reply to Erik Max Francis I'm
rethinking that decision. It can be handled a different way by making
a class responsible for deciding whether to copy or not - e.g. the
Builder class I used in that reply.

Looking at your example above, I see further evidence that the
rationale is false. Basically, it would be too easy to forget to
ensure the 'ref' was used in every method where it was needed - having
the rebinding to a proxy in a private internal method called by the
public methods would give a false sense of security.





More information about the Python-list mailing list