Compound Assignment Operators ( +=, *=, etc...)

Tom Christiansen tchrist at mox.perl.com
Sat Aug 14 14:35:28 EDT 1999


     [courtesy cc of this posting mailed to cited author]

In comp.lang.python, Drew McDowell <drew.mcdowell at msfc.nasa.gov> writes:
:I looked in the FAQ and couldn't find anything on the Compound Assignment
:Operators.  (+=, *=, -=, etc..)  Why dosen't Python support them?
:Is there a easy way to add them?

Well, to start with, Python does not even *have* an assignment operator.
Nope, not one.  Assignment is a statement, not an operator.  That's while
you can't write:

    while line = file.readline():
	print line

for example.

Mostly it's the old "burnt child fears fire" syndrome.  Or, if you would,
"fool me once, shame on you; fool me twice, shame on me".  By outlawing
it, you can't get burned/fooled by it.  Too many horrendous C programming
errors happen from confusing:

    while (var = function()) { }

with 

    while (var == function()) { }

Think of the classic loop:

    while ((ch = getchar()) != EOF) { } 

You end up having to use parentheses in do group the assignment,
and then test its result.

As for why you can't write the statement (note: not the expression)

    x["every"]["good"]["boy"]["does"]["fine"] =  (
	x["every"]["good"]["boy"]["does"]["fine"] + 1 )

as 

    x["every"]["good"]["boy"]["does"]["fine"] += 1

The basic reason seems to be that there are some people who believe that
this kind of thing is cruel and unusual punishment levied upon the poor
Pascal(ish) programmers purely for sake of brevity.

Common arguments in support of such ops include:

    1) This requires care to avoid mis-duplication:
	x["every"]["good"]["boy"]["does"]["fine"] =  (
	    x["every"]["good"]["boy"]["deos"]["fine"] + 1 )
    2) Side effects must be duplicated:
	x[every()][good()][boy()][does()][fine()] =  (
	    x[every()][good()][boy()][does()][fine()] + 1 )
    3) It's too long to type.
    4) Needless redundancy obscures the real meaning.

Whereas common rebuttals include:

    1) Toss /bin/ed and get yourself a real editor.
    2) Don't use side-effects, you wicked creature, you!
    3) It's more efficient to keep a tmpobj anyway.
    4) Redundancy can clarify through redundancy.

As to why there's no x++ there, consider how often people from a
Pascal(ish) background are confused between x+1 and x++ and ++x, and
you'll begin to see what kind of problems caused it to be vetoed.

But the best reason is probably the one another poster already supplied:
because Guido didn't like them.  An interesting study would be to check
the extent to which he also forbids such constructs in his own C code. :-)

--tom
-- 
    Besides, REAL computers have a rename() system call.    :-)
                    --Larry Wall in <7937 at jpl-devvax.JPL.NASA.GOV>




More information about the Python-list mailing list