The CPython reference interpreter has no such features; the optimizer it has is extremely limited, and generally can't perform inter-statement optimizations; by the the optimizer is looking at work -= 1
, it's forgotten all about work += 1
.
Cython may or may not be able to optimize this; I'd suspect it wouldn't on its own, but if the types were properly declared, the C compiler that compiles the code Cython generates might be able to eliminate the unused code.
For other interpreters (PyPy, Jython, IronPython), it's all going to depend on the quality of their JIT compilation engines. Odds are if the code is executed only once they won't bother to JIT it, but if it's hot code, executed many times, it might be able to eliminate the loop.
It's harder to do this in Python largely because even a loop as simple as the one you express can have unpredictable side-effects. Sure, on its face it's safe to drop the loop (if nothing reads from x
later anyway), but it's always possible the loop could be entered with xrange
replaced, either in module global or built-in scope, and the replacement might have observable side-effects. It makes it close to impossible to do static compilation of code without simply ignoring the possibility of xrange
being replaced (as Cython does) or compiling code that executes conditionally on xrange
not being replaced (as a careful JIT would have to).