[Python-ideas] Arbitrary constants in ASTs

Jonathan Brandvein jon.brandvein at gmail.com
Wed Jul 24 03:35:40 CEST 2013


In the deprecated (removed in Python 3) compiler library, it was possible
to construct a "Const" AST node. This node took in an arbitrary Python
object, and got compiled to a LOAD_CONST opcode. This functionality is not
available with the modern ast library. I wonder if there are any objections
to adding it.

Embedding objects in the AST can be handy. In a program transformation, you
can avoid having to create code to define and assign to a new variable
name. In code that is meant for exec or eval, you don't need to add the
object to the global or local namespaces that you pass in.

You also avoid the runtime overhead of a global namespace lookup, although
your semantics are slightly different in that the object cannot be replaced
at runtime. For a program transformation that introduces its own fixed
objects that are not meant to be hot-swapped or monkey patched, this is a
good tradeoff.

I bring this up because I just ported a project from Python 2.4 to 3.3, and
this was one feature where there was no good modern substitute available.

The one drawback I can think of is that there is no general canonical
source representation for an arbitrary constant. I will note that there are
already ASTs that don't have a unique source representation: think of two
ast.Name nodes that differ in their Store/Load context.

Are there any limitations in CPython concerning what values can be placed
in co_consts and accessed by LOAD_CONST?


Jon
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130723/ab34decc/attachment.html>


More information about the Python-ideas mailing list