When starting CPython from the command line you can pass the -O option
to enable optimisations (eg `assert 0` won't raise an exception when
-O is passed). But, AFAIK, there is no way to change the optimisation
level after the interpreter has started up, ie there is no Python
function call or variable that can change the optimisation.
In MicroPython we want to be able to change the optimisation level
from within a script because (on bare metal at least) there is no
analog of passing options like -O.
My idea would be to have a function like `sys.optimise(value)` that
sets the optimisation level for all subsequent runs of the
parser/compiler. For example:
import mymodule # no optimisations
exec('assert 0') # will raise an exception
sys.optimise(1) # enable optimisations
import myothermodule # optimisations are enabled for this (unless it's
already imported by mymodule)
exec('assert 0') # will not raise an exception
What do you think? Sorry if this has been discussed before!
I don't know if it's been discussed, but I have thought about it in context of PEP 511. The problem with swapping optimization levels post-start is that you end up with inconsistencies, e.g. asserts that depend on other asserts/__debug__ to function properly. If you let people jump around you potentially will break code in odd ways. Now obviously that's not necessarily a reason to not allow it, but it is something to consider.
Where this does become a potential issue in the future is if we ever start to have optimizations that span modules, e.g. function inlining and the such. We don't have support for this now, but if we ever make it easier to do such things then the ability to change the optimization level mid-execution would break assumptions or flat-out ban cross-module optimizations in fear that too much code would break.
So I'm not flat-out saying no to this idea, but there are some things to consider first.