anything like C++ references?

Ian Bicking ianb at colorstudy.com
Sun Jul 13 21:18:25 EDT 2003


I don't know why I'm participating, but it's feels hard to stay out of
this one...

On Sun, 2003-07-13 at 17:17, Martin v. Löwis wrote
> > 3.  Why is there no way to reference an immutable object via a
> > pointer, other than stuffing it into a mutable object designed for
> > some purpose other than simple pointer behaviour?
> 
> But there is: If I do
> 
> a = 1
> b = a
> 
> then b *refers* the same value that a refers to. That is, the values
> associated with a and b have the same identity.

I think, then, that Stephen maybe wants to do something like:

>>> a = ref(1)
>>> b = a
>>> b is a
True
>>> a + 2
3
>>> a = 5
>>> b
5

And so on.  This is all quite doable in Python (implementation of ref
left to the reader), except for the "a = 5" part.  Instead you'd have to
do something like "a.set(5)".  Even though it is doable, of course, it's
by way of clever hacks.

The problem that Stephen is not appreciating is that this sort of
reference implies that "a" is a typed variable -- of type "pointer",
somehow implicitly declared when it was initially assigned a ref
object.  (He's not alone, because just a little while ago someone
proposed a way to overload the meaning of "=", to achieve largely the
same functionality)  

It might not be quite as ugly-seeming if we explicitly declared "a" as a
pointer.  Besides the disinclination of people to add variable
declarations (though "global" already is one), it's more difficult
because there's now a new type that has to be usable everywhere, the
pointer type.  All Python's code that expected, say, integers would have
to also be ready to dereference the argument and then use it.  It could
probably be made seamless at the Python level fairly easily, but the C
would be annoying, no doubt.

One might think you could just use the references that already exists
(since variables are references, and everything is passed by
reference).  But that's messed up, because that'd mean:

>>> b = 2
>>> pointer a
>>> a = 2
>>> a is b
True
>>> a = 5
>>> b
5

The ability to redefine the integers is obviously not a good feature
(though I remember someone saying you can accidentally do some stuff
like this in C extensions).

Anyway, that's my attempt at empathy with Stephen, if not agreement.  If
he is wanting something other than what I've described, he should give
other examples, because code examples are better than words.

  Ian







More information about the Python-list mailing list