Is it possible to produce Python bytecode programmatically?

abstract-syntax-tree bytecode dsl expression-trees python

Question

With the Python interpreter, I want to experiment and see if I can make a simple DSL. Is there a module that allows me to execute this hypothetical code in a manner like to LINQ expression trees?

expression_tree = Function(
    Print(
        String('Hello world!')
    )
 )
compile_to_bytecode(expression_tree)

Or would just generating Python source code be simpler? Could Cython, SWIG, or C be used to simplify this?

1
11
8/9/2010 7:31:44 AM

Accepted Answer

working withast and creating sources and assembling them is nearly as good as turning the tree into bytecode, as another solution proposes.

Check out the links from this website to learn more about lower-level strategies, however; I found byteplay to be particularly helpful (it now only works on 2.4 or 2.5, not 2.6 nor 3.*, but changing it for 2.6 should be simple, as is being discussed in its tracker). Although I haven't tried Phil Eby's BytecodeAssembler, which has a lot of the same features, I'm sure it's worthwhile to check out given the author's repute.

11
9/27/2009 12:35:35 AM

Popular Answer

You would generally handle this in Python 2.X using the compiler module and itsast sub-module (but note this module is deprecated since version 2.6). You would simply use ast in Python 3.X.

Both provide acompile() method that will convert an executable code object from the source or AST toexec assertion oreval() ."



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow