[Python-ideas] Changing optimisation level from a script

Brett Cannon brett at python.org
Fri Sep 9 13:20:29 EDT 2016


On Thu, 8 Sep 2016 at 21:36 Damien George <damien.p.george at gmail.com> wrote:

> Hi all,
>
> 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 sys
> 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160909/e5660c45/attachment-0001.html>


More information about the Python-ideas mailing list