[Python-Dev] ++x oddness

M.-A. Lemburg mal@lemburg.com
Mon, 13 Aug 2001 20:36:47 +0200

Guido van Rossum wrote:
> > How?  ++x compiles to
> >
> >          LOAD_FAST         x
> >          UNARY_POSITIVE
> >          UNARY_POSITIVE
> >
> > I don't see any incrementing going on...
> I'm guessing that MAL used a perverse implementation trick, where for
> a certain *mutable* counter type '+x' returns an object that contains
> a reference to x, and the unary plus operation on *that* object
> increments the counter it references.

Well, not quite that complicated: the type counts the number of calls
to __pos__ and then increments the value in every second call.

It was just an implementation joke and proof of concept thingie.
The idea behind it was to be able to increment the counter (which
is the most often used action on a counter after all) without having
to go through the whole Python method lookup and call machinery.
> Twisted, sick, call it what you want -- but please don't get used to
> this.  The likelihood that I'll ever add a ++ operator is very small,
> but not zero. :-)

Ah, but then you'll have to add it as post-fix operator: x++ (which is
illegal today). The difference between ++x and x++ isn't needed in
Python anyway, so this should work out nicely.

Hmm, x++ could map directly to the tp_iternext slot on iterator 
objects... ;-)

Marc-Andre Lemburg
CEO eGenix.com Software GmbH
Consulting & Company:                           http://www.egenix.com/
Python Software:                        http://www.lemburg.com/python/