[Python-ideas] Changing optimisation level from a script

Guido van Rossum guido at python.org
Fri Sep 9 15:02:19 EDT 2016


I very much doubt that one assert might depend on another, and if they
do, we can just tell people not to change the debug level. The API to
change this should set __debug__ appropriately.

On Fri, Sep 9, 2016 at 10:20 AM, Brett Cannon <brett at python.org> wrote:
>
>
> 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.
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/



-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list