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

James Y Knight foom at fuhm.net
Mon Jun 13 05:42:45 CEST 2005


On Jun 12, 2005, at 10:20 PM, Raymond Hettinger wrote:
> 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).

Yes, changing the semantics of the if statement would be pretty bad.  
Unless evaluating x provably has no side effects (e.g. accessing a  
local variable), I would say that the duplicate evaluations must not  
be eliminated.


>>     if x == 1:
>>         print 1
>>     elif x == 2:
>>         print 2
>>     else:
>>         print "unknown"

Unfortunately, I'm afraid this will not be as useful as it at first  
appears, because python has no concept of a constant variable  
binding. I hardly ever see an if/else chain being done with hardcoded  
integers. Rather, more often a variable is compared to global  
"constants", which could not be optimized away. However, this  
construction does appear reasonably often with constant strings on  
the RHS, so there may actually be a real-world gain to be had.

With a Sufficiently Smart Compiler, of course, you could make  
assumptions at runtime about values not changing, and recompile code  
depending upon that assumption if necessary, but that's more in the  
realm of a new runtime than modifications to CPython. Maybe PyPy will  
eventually provide the ability to do that kind of interesting  
optimization.

James


More information about the Python-Dev mailing list