This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients benjamin.peterson, brett.cannon, serhiy.storchaka, vstinner
Date 2016-01-18.17:04:48
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Currently, the Python parser emits ast.Tuple AST nodes which are compiled to multiple LOAD_xxx instructions followed a final BUILD_TUPLE instruction. The Python peephole optimizer detect LOAD_CONST x n + BUILD_TUPLE instructions to replace it directly with a tuple constant.

IHMO it's better to implement this optimization early at the AST level in an AST optimizer. The PEP 511 proposes to add a new ast.Constant AST node for that.

With this new AST node, the AST optimizer can emit tuple constants, but also any kind of constant like frozenset. For example, it's also possible to optimize "x in {1, 2}" to "x in frozenset({1, 2})" where frozenset({1, 2}) is a constant (don't call frozenset type at runtime). (Again, this optimization is already implemented in the peephole optimizer, it's just an example.)

Attached patch adds the new ast.Constant type but update also code consuming AST to handle this new kind of node:

* add the node: Parser/Python.asdl, Parser/, Parser/
* generated changes: Include/asdl.h, Include/Python-ast.h, Python/Python-ast.c
* accept the node kind: Python/symtable.c, Python/ast.c
* accept Constant instead of Num or Str: Lib/, Python/future.c, Tools/parser/
* emit constants to bytecode: Python/compile.c

I didn't change the compiler to emit directly ast.Constant nodes to reduce the impact on the backward compatibility. This change can be done. An AST optimizer is responsible to convert NameConstant (False, True, None), Num (int, float, complex), Str, Bytes, Tuple to Constant. Example with fatoptimizer:

ast.Constant also simplifies AST optimizers: no need to check each time if a node is constant or not.

Adding a new kind of node was already proposed in the old issue #11549: the patch adds ast.Lit (it was proposed to rename it to ast.Literal).
Date User Action Args
2016-01-18 17:04:53vstinnersetrecipients: + vstinner, brett.cannon, benjamin.peterson, serhiy.storchaka
2016-01-18 17:04:51vstinnersetmessageid: <>
2016-01-18 17:04:51vstinnerlinkissue26146 messages
2016-01-18 17:04:51vstinnercreate