Yurttas/PL/SL/python/docs/core-python-programming/doc/20/lib/node376.html

From ZCubes Wiki
Revision as of 19:57, 7 November 2013 by MassBot1 (talk | contribs) (Created page with "<div class="navigation"> {| width="100%" cellspacing="2" align="center" | yurttas/PL/SL/python/docs/core-python-programming/doc/20/lib/AST Examples.html|[[Image:yurttas...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

17.1.6.1 Emulation of compile()

While many useful operations may take place between parsing and bytecode generation, the simplest operation is to do nothing. For this purpose, using the parser module to produce an intermediate data structure is equivalent to the code

>>> code = compile('a + 5', 'file.py', 'eval')
>>> a = 5
>>> eval(code)
10

The equivalent operation using the parser module is somewhat longer, and allows the intermediate internal parse tree to be retained as an AST object:

>>> import parser
>>> ast = parser.expr('a + 5')
>>> code = ast.compile('file.py')
>>> a = 5
>>> eval(code)
10

An application which needs both AST and code objects can package this code into readily available functions:

import parser

def load_suite(source_string):
    ast = parser.suite(source_string)
    return ast, ast.compile()

def load_expression(source_string):
    ast = parser.expr(source_string)
    return ast, ast.compile()

See About this document... for information on suggesting changes.