I would like to assemble Python 'ast.Module' objects inside of Mathematica and then submit them to Python via e.g. ExternalEvaluate["exec(astObject)"]
.
The Python ast, parse, eval, exec and compile functions can all operate on 'ast.Module' objects, either outputting them or taking them as inputs. However I don't know how to assemble this astObject
within Mathematica/WL and then send it over to Python via ExternalEvaluate
.
I am trying to programmatically generate Python code in MMA (for a genetic algorithm) and then submit it to Python for evaluation. I could assemble Python code strings, but then I have to handle all of the indentation, which seems like a pain.
For example, in Python it is possible to do the following:
import ast
pythonString="X3=X1*X2"
astObject=ast.parse(pythonString)
X1=3
X2=4
exec(compile(astObject,"","exec"))
print(X3)
-> 12
And of course from MMA it is possible to do:
session=StartExternalSession["Python"]
ExternalEvaluate[session, {"import ast","X1=3","X2=4",
"exec(compile(ast.parse(\"X3=X1*X2\"),\"\",\"exec\"))"} ]
to yield the same result (i.e. 12).
However I want to generate my bits of Python code ("X1=3"
,"X2=4"
,"X3=X1*X2"
) in Mathematica. These bits here are simple enough, but I intend to generate complete programs, i.e. statements and expressions, metaprogrammatically(!). To do that I then have to figure out how to parse Python's annoying indentations, which is of course how it distinguishes one set of expressions from the next and what their dependencies are. I am loath to do so, and figured that it might be easier to operate on the ast structure.
Originally I had thought I might be able to use an intermediate string-form from Python's ast.dump()
function which looks like:
astString = ast.dump(pythonString)
-> "Module(Body=[Assign(targets=[Name(id='X3',ctx=Store())],value=BinOp(left=Name(id='X1',
ctx=Load()),op=Mult(),right=Name(id='X2',ctx=Load())))])"
and since this astString
essentially serializes the astObject
I could also generate this instead. However I cannot find any way of getting Python to do anything with this astString
.
Is it possible to create this sort of Python object - like my astObject
above - on the Mathematica side?
B
PS: Here is a description of the 'ast.Module' objects: https://greentreesnakes.readthedocs.io/en/latest/tofrom.html
PPS: I have cross-posted this on Wolfram Community: https://community.wolfram.com/groups/-/m/t/2070851
LSAMon
. (Scroll to the bottom.) $\endgroup$