Pass-by-reference : Could a C#-like approach work in Python?
Peter Otten
__peter__ at web.de
Wed Sep 10 18:50:29 EDT 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)
def fun(o):
nested(ref o)
# so glad we can do no harm to o...riginal
x = C()
fun(x)
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__
Exception: read-only
>>> c.x
1
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.
Peter
More information about the Python-list
mailing list