[Python-Dev] Multiple expression eval in compound if statement?

Michael Chermside mcherm at mcherm.com
Mon Jun 13 14:07:32 CEST 2005


A few thought's on Skip's idea here:

Skip:
> I can't imagine anyone relying on a side-effect when evaluating x in this
> context, and if someone did, their code would be truly fragile.

Yeah... people like that really annoy me. If people just wouldn't write code
that depends on the FULL dynamics possible, then it'd be a lot easier for
the VM to optimize. Unfortunately, we have to support such people.

Raymond:
I think it unwise to allow x to be any expression.  Besides altering
existing semantics, it leads to code redundancy and to a fragile
construct (where the slightest alteration of any of the expressions
triggers a silent reversion to O(n) behavior).

Skip's proposal isn't the problem here. The syntax of the if-elif-else
statement requires that when it is used in lieu of C's switch() statement
that the switch() argument be repeated in each elif clause. Repeating
it DOES violate once-and-only-once, but we've decided that that's an
acceptable price to pay to avoid needing an extra kind of flow control
statement for which there wasn't a really elegent syntax anyhow. A
reasonably tradeoff, I agree, but the cost is that we DO violate
once-and-only-once. The REAL danger from the "slightest alteration of
any of the expressions" is not that it will alter from O(1) behavior
to O(n) behavior, the REAL danger is that you may have MEANT it to be
the same everywhere and the alteration is a typo and a bug!

Guido:
> I think it would be wiser if you only did this when x is a simple
> local variable.

I agree. I think of Skip's proposal as just an optimization, of the
sort that the Python interpreter is allowed to make when there's no
possible semantic effect. It would then restrict the use to situations
where the 'switch() argument' was a local variable and the 'case values'
were string literals, integer literals, float literals (but that
shouldn't count because it's a really bad idea anyhow), None, and
perhaps (I wouldn't bother, myself) tuples of the above. It sounds
pretty restricted, which raises the question of whether it's worth it
given the harsh restrictions on when the optimization would kick in.

I write such things with local variables and literal strings quite often.
On the other hand, I don't usually have more than 4-10 values though, so
O(1) and O(n) may not be THAT different. It's one of those cases where the
only thing I'd really believe was experiments done on real code. But it's
a cool optimization if it actually pays off.

-- Michael Chermside



More information about the Python-Dev mailing list