{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Accessing Python Syntax Trees" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to access code that is written in Python. This works using the `ast` module, and works as follows:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Module(body=[FunctionDef(name='f', args=arguments(args=[arg(arg='x', annotation=None), arg(arg='y', annotation=None)], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Return(value=BinOp(left=BinOp(left=BinOp(left=Num(n=2), op=Mult(), right=Name(id='x', ctx=Load())), op=Add(), right=BinOp(left=Name(id='y', ctx=Load()), op=Pow(), right=Num(n=2))), op=Add(), right=Num(n=5)))], decorator_list=[], returns=None)])\n" ] } ], "source": [ "SRC = \"\"\"\n", "def f(x, y):\n", " return 2*x + y**2 + 5\n", "\"\"\"\n", "\n", "import ast\n", "tree = ast.parse(SRC)\n", "\n", "print(ast.dump(tree))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to transcribe the expressions here into the form discussed earlier." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2*x + y**2 + 5\n" ] } ], "source": [ "from pymbolic.interop.ast import ASTToPymbolic\n", "expr = ASTToPymbolic()(tree.body[0].body[0].value)\n", "print(expr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But beware when defining languages this way. Python has very well-defined semantics, and the user will expect that your way of executing their code is a good match for their mental model of what the code should do. As such, it may be better to start with a \"blank slate\" in terms of language design, so as to not run afoul of already formed expectations." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.0+" } }, "nbformat": 4, "nbformat_minor": 0 }