4 ms·
The local variable elimination optimization breaks introspection features. def foo(): a=1 return a Then we can inspect the local variables:
by kccqzy 8y ago
The local variable elimination optimization breaks introspection features.
def foo():
a=1
return a
Then we can inspect the local variables:
print(foo.__code__.co_nlocals)
print(foo.__code__.co_varnames)
On a related note, I believe it was also a deliberate decision to keep the name of all local variables during compilation. This is of course very different from C.
- greglindahl 8y agoActually, C compilers with -O0 keep all of the local variables, for debugging purposes. O0 is deliberately bad. And if you file bugs complaining about debugging at higher optimization levels, well, if you want loop fusion and splitting for high performance, you're going to lose some debugging.
- aasasd 8y agoI wonder if Python could similarly have opt-in optimization (‘-Osomething’) for those who are sure it won't break anything. Though I guess the standard lib might get in the way immediately.
- masklinn 8y agoCPython already has -O and -OO, they just don't do much that's useful (and are mostly detrimental): -O will skip asserts and set __debug__ to False, -OO will also remove docstrings. CPython's compilation pipeline just has a fairly straightforward peephole optimiser: https://github.com/python/cpython/blob/master/Python/peephole.c https://github.com/python/cpython/blob/master/Python/peephol...
- greglindahl 8y agoYou're describing opt-in pessmisation, not opt-in optimization.
- kccqzy 8y agoNo that's qualitatively different. There's no way for a piece of C code to look at the local variables of another C function. But in Python you can do that. What you mean is that C compilers keep the local variables on the stack, and do not eliminate loads/stores so that a debugger can see what the variables are and a debugger can read DWARF information to figure out names of variables. There is no way for code itself to learn these except for implementing DWARF parsing yourself.
- kazinator 8y agoThat's an incredibly stupid thing to put into production code, though and should be regarded as a debugging feature. It's acceptable to have different compilation modes for different levels/fidelities of debugging introspection.