On 6/12/05, Skip Montanaro <[EMAIL PROTECTED]> wrote: > > I'm horsing around with recognizing switch-like if statements like: > > if x == 1: > print 1 > elif x == 2: > print 2 > else: > print "unknown" > > in the compiler and generating O(1) code. "x" can be any expression, but > must be precisely the same in each elif clause, the comparison operator must > be "==" and the RHS of the test must evaluate to a simple hashable constant > (string, float, integer - still working on None, constant tuples may be > allowed later). I can currently recognize such constructs and am working on > code generation.
Cool! > This would represent a semantic change to the Python runtime, because x > would only be evaluated once, whereas in existing usage it can potentially > be evaluated many times. If evaluating x has side-effects, code like the > above that currently works would break. > > In reading the language reference manual, it says: > > It selects exactly one of the suites by evaluating the expressions one > by one until one is found to be true (see section 5.10 for the > definition of true and false); then that suite is executed (and no other > part of the if statement is executed or evaluated). If all expressions > are false, the suite of the else clause, if present, is executed. > > It says nothing about possibly caching values, which is what I'm doing > effectively, but it seems pretty clear that each full test expression will > be evaluated until one evaluates to true. > > 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. Still, any > thought as to whether or not such a semantic change to the language might be > acceptable? I think it would be wiser if you only did this when x is a simple local variable. For locals, we *know* that no side effect of any expression can change the value. -- --Guido van Rossum (home page: http://www.python.org/~guido/) _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com