as i understand the compile() documentation ,
the above example should remove the docstring ,
and the assert line , but it doesn't .
setting the env var PYTHONOPTIMIZE=2 and then
running python with the cmdLine option -OO
this time with
a) compile( ... , dont_inherit=False , ... ) without optimize
b) compile( ... , dont_inherit=0 , ... ) without optimize
c) compile( ... ) without : dont_inherit , optimize
didn't chage the outcome :
compile() never removes docstrings/asserts .
looks like compile() ignores its arg optimize=2
and -OO and PYTHONOPTIMIZE=2 .
The doc says "The argument optimize specifies the optimization level of the compiler;". With the PyCF_ONLY_AST, you are only running the parser, not the compiler itself. If the parser stripped docstrings and assert statements, then unparse would not work right. Also, def f(): "docstring"` would not compile as the docstring is, here, the required non-empty suite.
If you compile to a code object and exec the code object, the resulting test function object will not have a docstring or assert.
changed the title [-]compile(optimize=2 ) doesn't del docstrings/asserts , ignores -OO & PYTHONOPTIMIZE=2[/-][+]compile(optimize=2) doesn't del docstrings/asserts, ignores -OO & PYTHONOPTIMIZE=2[/+]on Dec 10, 2023
Activity
terryjreedy commented on Dec 10, 2023
The doc says "The argument optimize specifies the optimization level of the compiler;". With the PyCF_ONLY_AST, you are only running the parser, not the compiler itself. If the parser stripped docstrings and assert statements, then unparse would not work right. Also, def f(): "docstring"` would not compile as the docstring is, here, the required non-empty suite.
If you compile to a code object and exec the code object, the resulting test function object will not have a docstring or assert.
Perhaps the doc could be clearer to Python learners, but I am not sure how.
dreamflow commented on Dec 10, 2023
thank you terryjreedy for the detailed explanation 🙂
carljm commented on Dec 17, 2023
This is a duplicate of #108113. In #108154 @iritkatriel added PyCF_OPTIMIZED_AST to solve this (but for Python 3.13+ only.)