Keywords: lib

## 19.3.3 Examples

This section shows several simple examples of ASTs for Python source code. The examples demonstrate how to use the `parse()` function, what the repr of an AST looks like, and how to access attributes of an AST node.

The first module defines a single function. Assume it is stored in /tmp/doublelib.py.

      """This is an example module.

      This is the docstring.
      """

      def double(x):
          "Return twice the argument"
          return x * 2

In the interactive interpreter session below, I have reformatted the long AST reprs for readability. The AST reprs use unqualified class names. If you want to create an instance from a repr, you must import the class names from the `compiler.ast` module.

      >>> import compiler
      >>> mod = compiler.parseFile("/tmp/doublelib.py")
      >>> mod
      Module('This is an example module.\n\nThis is the docstring.\n',
             Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
             Stmt([Return(Mul((Name('x'), Const(2))))]))]))
      >>> from compiler.ast import *
      >>> Module('This is an example module.\n\nThis is the docstring.\n',
      ...    Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
      ...    Stmt([Return(Mul((Name('x'), Const(2))))]))]))
      Module('This is an example module.\n\nThis is the docstring.\n',
             Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
             Stmt([Return(Mul((Name('x'), Const(2))))]))]))
      >>> mod.doc
      'This is an example module.\n\nThis is the docstring.\n'
      >>> for node in mod.node.nodes:
      ...     print node
      ...
      Function('double', ['x'], [], 0, 'Return twice the argument',
               Stmt([Return(Mul((Name('x'), Const(2))))]))
      >>> func = mod.node.nodes[0]
      >>> func.code
      Stmt([Return(Mul((Name('x'), Const(2))))])