Pass-by-reference : Could a C#-like approach work in Python?
__peter__ at web.de
Thu Sep 11 00:50:29 CEST 2003
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)
# so glad we can do no harm to o...riginal
x = C()
x.attr = newValue # oops
Note that even in today's Python you can do weird stuff:
>>> class C: pass
>>> class D:
... def __setattr__(self, n, v): raise Exception, "read-only"
>>> c = C()
>>> c.x = 1
>>> c.__class__ = D
>>> c.y = 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in __setattr__
This would at least propagate over the entire calling hierarchy.
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.
More information about the Python-list