2 :mod:`parser` --- Access Python parse trees
3 ===========================================
6 :synopsis: Access parse trees for Python source code.
7 .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
11 .. Copyright 1995 Virginia Polytechnic Institute and State University and Fred
12 L. Drake, Jr. This copyright notice must be distributed on all copies, but
13 this document otherwise may be distributed as part of the Python
14 distribution. No fee may be charged for this document in any representation,
15 either on paper or electronically. This restriction does not affect other
16 elements in a distributed package in any way.
18 .. index:: single: parsing; Python source code
20 The :mod:`parser` module provides an interface to Python's internal parser and
21 byte-code compiler. The primary purpose for this interface is to allow Python
22 code to edit the parse tree of a Python expression and create executable code
23 from this. This is better than trying to parse and modify an arbitrary Python
24 code fragment as a string because parsing is performed in a manner identical to
25 the code forming the application. It is also faster.
27 There are a few things to note about this module which are important to making
28 use of the data structures created. This is not a tutorial on editing the parse
29 trees for Python code, but some examples of using the :mod:`parser` module are
32 Most importantly, a good understanding of the Python grammar processed by the
33 internal parser is required. For full information on the language syntax, refer
34 to :ref:`reference-index`. The parser
35 itself is created from a grammar specification defined in the file
36 :file:`Grammar/Grammar` in the standard Python distribution. The parse trees
37 stored in the AST objects created by this module are the actual output from the
38 internal parser when created by the :func:`expr` or :func:`suite` functions,
39 described below. The AST objects created by :func:`sequence2ast` faithfully
40 simulate those structures. Be aware that the values of the sequences which are
41 considered "correct" will vary from one version of Python to another as the
42 formal grammar for the language is revised. However, transporting code from one
43 Python version to another as source text will always allow correct parse trees
44 to be created in the target version, with the only restriction being that
45 migrating to an older version of the interpreter will not support more recent
46 language constructs. The parse trees are not typically compatible from one
47 version to another, whereas source code has always been forward-compatible.
49 Each element of the sequences returned by :func:`ast2list` or :func:`ast2tuple`
50 has a simple form. Sequences representing non-terminal elements in the grammar
51 always have a length greater than one. The first element is an integer which
52 identifies a production in the grammar. These integers are given symbolic names
53 in the C header file :file:`Include/graminit.h` and the Python module
54 :mod:`symbol`. Each additional element of the sequence represents a component
55 of the production as recognized in the input string: these are always sequences
56 which have the same form as the parent. An important aspect of this structure
57 which should be noted is that keywords used to identify the parent node type,
58 such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the
59 node tree without any special treatment. For example, the :keyword:`if` keyword
60 is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value
61 associated with all :const:`NAME` tokens, including variable and function names
62 defined by the user. In an alternate form returned when line number information
63 is requested, the same token might be represented as ``(1, 'if', 12)``, where
64 the ``12`` represents the line number at which the terminal symbol was found.
66 Terminal elements are represented in much the same way, but without any child
67 elements and the addition of the source text which was identified. The example
68 of the :keyword:`if` keyword above is representative. The various types of
69 terminal symbols are defined in the C header file :file:`Include/token.h` and
70 the Python module :mod:`token`.
72 The AST objects are not required to support the functionality of this module,
73 but are provided for three purposes: to allow an application to amortize the
74 cost of processing complex parse trees, to provide a parse tree representation
75 which conserves memory space when compared to the Python list or tuple
76 representation, and to ease the creation of additional modules in C which
77 manipulate parse trees. A simple "wrapper" class may be created in Python to
78 hide the use of AST objects.
80 The :mod:`parser` module defines functions for a few distinct purposes. The
81 most important purposes are to create AST objects and to convert AST objects to
82 other representations such as parse trees and compiled code objects, but there
83 are also functions which serve to query the type of parse tree represented by an
90 Useful constants representing internal nodes of the parse tree.
93 Useful constants representing leaf nodes of the parse tree and functions for
102 AST objects may be created from source code or from a parse tree. When creating
103 an AST object from source, different functions are used to create the ``'eval'``
104 and ``'exec'`` forms.
107 .. function:: expr(source)
109 The :func:`expr` function parses the parameter *source* as if it were an input
110 to ``compile(source, 'file.py', 'eval')``. If the parse succeeds, an AST object
111 is created to hold the internal parse tree representation, otherwise an
112 appropriate exception is thrown.
115 .. function:: suite(source)
117 The :func:`suite` function parses the parameter *source* as if it were an input
118 to ``compile(source, 'file.py', 'exec')``. If the parse succeeds, an AST object
119 is created to hold the internal parse tree representation, otherwise an
120 appropriate exception is thrown.
123 .. function:: sequence2ast(sequence)
125 This function accepts a parse tree represented as a sequence and builds an
126 internal representation if possible. If it can validate that the tree conforms
127 to the Python grammar and all nodes are valid node types in the host version of
128 Python, an AST object is created from the internal representation and returned
129 to the called. If there is a problem creating the internal representation, or
130 if the tree cannot be validated, a :exc:`ParserError` exception is thrown. An
131 AST object created this way should not be assumed to compile correctly; normal
132 exceptions thrown by compilation may still be initiated when the AST object is
133 passed to :func:`compileast`. This may indicate problems not related to syntax
134 (such as a :exc:`MemoryError` exception), but may also be due to constructs such
135 as the result of parsing ``del f(0)``, which escapes the Python parser but is
136 checked by the bytecode compiler.
138 Sequences representing terminal tokens may be represented as either two-element
139 lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1,
140 'name', 56)``. If the third element is present, it is assumed to be a valid
141 line number. The line number may be specified for any subset of the terminal
142 symbols in the input tree.
145 .. function:: tuple2ast(sequence)
147 This is the same function as :func:`sequence2ast`. This entry point is
148 maintained for backward compatibility.
153 Converting AST Objects
154 ----------------------
156 AST objects, regardless of the input used to create them, may be converted to
157 parse trees represented as list- or tuple- trees, or may be compiled into
158 executable code objects. Parse trees may be extracted with or without line
159 numbering information.
162 .. function:: ast2list(ast[, line_info])
164 This function accepts an AST object from the caller in *ast* and returns a
165 Python list representing the equivalent parse tree. The resulting list
166 representation can be used for inspection or the creation of a new parse tree in
167 list form. This function does not fail so long as memory is available to build
168 the list representation. If the parse tree will only be used for inspection,
169 :func:`ast2tuple` should be used instead to reduce memory consumption and
170 fragmentation. When the list representation is required, this function is
171 significantly faster than retrieving a tuple representation and converting that
174 If *line_info* is true, line number information will be included for all
175 terminal tokens as a third element of the list representing the token. Note
176 that the line number provided specifies the line on which the token *ends*.
177 This information is omitted if the flag is false or omitted.
180 .. function:: ast2tuple(ast[, line_info])
182 This function accepts an AST object from the caller in *ast* and returns a
183 Python tuple representing the equivalent parse tree. Other than returning a
184 tuple instead of a list, this function is identical to :func:`ast2list`.
186 If *line_info* is true, line number information will be included for all
187 terminal tokens as a third element of the list representing the token. This
188 information is omitted if the flag is false or omitted.
191 .. function:: compileast(ast[, filename='<ast>'])
193 .. index:: builtin: eval
195 The Python byte compiler can be invoked on an AST object to produce code objects
196 which can be used as part of an :keyword:`exec` statement or a call to the
197 built-in :func:`eval` function. This function provides the interface to the
198 compiler, passing the internal parse tree from *ast* to the parser, using the
199 source file name specified by the *filename* parameter. The default value
200 supplied for *filename* indicates that the source was an AST object.
202 Compiling an AST object may result in exceptions related to compilation; an
203 example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``:
204 this statement is considered legal within the formal grammar for Python but is
205 not a legal language construct. The :exc:`SyntaxError` raised for this
206 condition is actually generated by the Python byte-compiler normally, which is
207 why it can be raised at this point by the :mod:`parser` module. Most causes of
208 compilation failure can be diagnosed programmatically by inspection of the parse
214 Queries on AST Objects
215 ----------------------
217 Two functions are provided which allow an application to determine if an AST was
218 created as an expression or a suite. Neither of these functions can be used to
219 determine if an AST was created from source code via :func:`expr` or
220 :func:`suite` or from a parse tree via :func:`sequence2ast`.
223 .. function:: isexpr(ast)
225 .. index:: builtin: compile
227 When *ast* represents an ``'eval'`` form, this function returns true, otherwise
228 it returns false. This is useful, since code objects normally cannot be queried
229 for this information using existing built-in functions. Note that the code
230 objects created by :func:`compileast` cannot be queried like this either, and
231 are identical to those created by the built-in :func:`compile` function.
234 .. function:: issuite(ast)
236 This function mirrors :func:`isexpr` in that it reports whether an AST object
237 represents an ``'exec'`` form, commonly known as a "suite." It is not safe to
238 assume that this function is equivalent to ``not isexpr(ast)``, as additional
239 syntactic fragments may be supported in the future.
244 Exceptions and Error Handling
245 -----------------------------
247 The parser module defines a single exception, but may also pass other built-in
248 exceptions from other portions of the Python runtime environment. See each
249 function for information about the exceptions it can raise.
252 .. exception:: ParserError
254 Exception raised when a failure occurs within the parser module. This is
255 generally produced for validation failures rather than the built in
256 :exc:`SyntaxError` thrown during normal parsing. The exception argument is
257 either a string describing the reason of the failure or a tuple containing a
258 sequence causing the failure from a parse tree passed to :func:`sequence2ast`
259 and an explanatory string. Calls to :func:`sequence2ast` need to be able to
260 handle either type of exception, while calls to other functions in the module
261 will only need to be aware of the simple string values.
263 Note that the functions :func:`compileast`, :func:`expr`, and :func:`suite` may
264 throw exceptions which are normally thrown by the parsing and compilation
265 process. These include the built in exceptions :exc:`MemoryError`,
266 :exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`. In these
267 cases, these exceptions carry all the meaning normally associated with them.
268 Refer to the descriptions of each function for detailed information.
276 Ordered and equality comparisons are supported between AST objects. Pickling of
277 AST objects (using the :mod:`pickle` module) is also supported.
282 The type of the objects returned by :func:`expr`, :func:`suite` and
283 :func:`sequence2ast`.
285 AST objects have the following methods:
288 .. method:: AST.compile([filename])
290 Same as ``compileast(ast, filename)``.
293 .. method:: AST.isexpr()
295 Same as ``isexpr(ast)``.
298 .. method:: AST.issuite()
300 Same as ``issuite(ast)``.
303 .. method:: AST.tolist([line_info])
305 Same as ``ast2list(ast, line_info)``.
308 .. method:: AST.totuple([line_info])
310 Same as ``ast2tuple(ast, line_info)``.
318 .. index:: builtin: compile
320 The parser modules allows operations to be performed on the parse tree of Python
321 source code before the :term:`bytecode` is generated, and provides for inspection of the
322 parse tree for information gathering purposes. Two examples are presented. The
323 simple example demonstrates emulation of the :func:`compile` built-in function
324 and the complex example shows the use of a parse tree for information discovery.
327 Emulation of :func:`compile`
328 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
330 While many useful operations may take place between parsing and bytecode
331 generation, the simplest operation is to do nothing. For this purpose, using
332 the :mod:`parser` module to produce an intermediate data structure is equivalent
335 >>> code = compile('a + 5', 'file.py', 'eval')
340 The equivalent operation using the :mod:`parser` module is somewhat longer, and
341 allows the intermediate internal parse tree to be retained as an AST object::
344 >>> ast = parser.expr('a + 5')
345 >>> code = ast.compile('file.py')
350 An application which needs both AST and code objects can package this code into
351 readily available functions::
355 def load_suite(source_string):
356 ast = parser.suite(source_string)
357 return ast, ast.compile()
359 def load_expression(source_string):
360 ast = parser.expr(source_string)
361 return ast, ast.compile()
364 Information Discovery
365 ^^^^^^^^^^^^^^^^^^^^^
368 single: string; documentation
371 Some applications benefit from direct access to the parse tree. The remainder
372 of this section demonstrates how the parse tree provides access to module
373 documentation defined in docstrings without requiring that the code being
374 examined be loaded into a running interpreter via :keyword:`import`. This can
375 be very useful for performing analyses of untrusted code.
377 Generally, the example will demonstrate how the parse tree may be traversed to
378 distill interesting information. Two functions and a set of classes are
379 developed which provide programmatic access to high level function and class
380 definitions provided by a module. The classes extract information from the
381 parse tree and provide access to the information at a useful semantic level, one
382 function provides a simple low-level pattern matching capability, and the other
383 function defines a high-level interface to the classes by handling file
384 operations on behalf of the caller. All source files mentioned here which are
385 not part of the Python installation are located in the :file:`Demo/parser/`
386 directory of the distribution.
388 The dynamic nature of Python allows the programmer a great deal of flexibility,
389 but most modules need only a limited measure of this when defining classes,
390 functions, and methods. In this example, the only definitions that will be
391 considered are those which are defined in the top level of their context, e.g.,
392 a function defined by a :keyword:`def` statement at column zero of a module, but
393 not a function defined within a branch of an :keyword:`if` ... :keyword:`else`
394 construct, though there are some good reasons for doing so in some situations.
395 Nesting of definitions will be handled by the code developed in the example.
397 To construct the upper-level extraction methods, we need to know what the parse
398 tree structure looks like and how much of it we actually need to be concerned
399 about. Python uses a moderately deep parse tree so there are a large number of
400 intermediate nodes. It is important to read and understand the formal grammar
401 used by Python. This is specified in the file :file:`Grammar/Grammar` in the
402 distribution. Consider the simplest case of interest when searching for
403 docstrings: a module consisting of a docstring and nothing else. (See file
404 :file:`docstring.py`.) ::
406 """Some documentation.
409 Using the interpreter to take a look at the parse tree, we find a bewildering
410 mass of numbers and parentheses, with the documentation buried deep in nested
415 >>> ast = parser.suite(open('docstring.py').read())
416 >>> tup = ast.totuple()
417 >>> pprint.pprint(tup)
436 (300, (3, '"""Some documentation.\n"""'))))))))))))))))),
441 The numbers at the first element of each node in the tree are the node types;
442 they map directly to terminal and non-terminal symbols in the grammar.
443 Unfortunately, they are represented as integers in the internal representation,
444 and the Python structures generated do not change that. However, the
445 :mod:`symbol` and :mod:`token` modules provide symbolic names for the node types
446 and dictionaries which map from the integers to the symbolic names for the node
449 In the output presented above, the outermost tuple contains four elements: the
450 integer ``257`` and three additional tuples. Node type ``257`` has the symbolic
451 name :const:`file_input`. Each of these inner tuples contains an integer as the
452 first element; these integers, ``264``, ``4``, and ``0``, represent the node
453 types :const:`stmt`, :const:`NEWLINE`, and :const:`ENDMARKER`, respectively.
454 Note that these values may change depending on the version of Python you are
455 using; consult :file:`symbol.py` and :file:`token.py` for details of the
456 mapping. It should be fairly clear that the outermost node is related primarily
457 to the input source rather than the contents of the file, and may be disregarded
458 for the moment. The :const:`stmt` node is much more interesting. In
459 particular, all docstrings are found in subtrees which are formed exactly as
460 this node is formed, with the only difference being the string itself. The
461 association between the docstring in a similar tree and the defined entity
462 (class, function, or module) which it describes is given by the position of the
463 docstring subtree within the tree defining the described structure.
465 By replacing the actual docstring with something to signify a variable component
466 of the tree, we allow a simple pattern matching approach to check any given
467 subtree for equivalence to the general pattern for docstrings. Since the
468 example demonstrates information extraction, we can safely require that the tree
469 be in tuple form rather than list form, allowing a simple variable
470 representation to be ``['variable_name']``. A simple recursive function can
471 implement the pattern matching, returning a Boolean and a dictionary of variable
472 name to value mappings. (See file :file:`example.py`.) ::
474 from types import ListType, TupleType
476 def match(pattern, data, vars=None):
479 if type(pattern) is ListType:
480 vars[pattern[0]] = data
482 if type(pattern) is not TupleType:
483 return (pattern == data), vars
484 if len(data) != len(pattern):
486 for pattern, data in map(None, pattern, data):
487 same, vars = match(pattern, data, vars)
492 Using this simple representation for syntactic variables and the symbolic node
493 types, the pattern for the candidate docstring subtrees becomes fairly readable.
494 (See file :file:`example.py`.) ::
499 DOCSTRING_STMT_PATTERN = (
518 (token.STRING, ['docstring'])
523 Using the :func:`match` function with this pattern, extracting the module
524 docstring from the parse tree created previously is easy::
526 >>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])
530 {'docstring': '"""Some documentation.\n"""'}
532 Once specific data can be extracted from a location where it is expected, the
533 question of where information can be expected needs to be answered. When
534 dealing with docstrings, the answer is fairly simple: the docstring is the first
535 :const:`stmt` node in a code block (:const:`file_input` or :const:`suite` node
536 types). A module consists of a single :const:`file_input` node, and class and
537 function definitions each contain exactly one :const:`suite` node. Classes and
538 functions are readily identified as subtrees of code block nodes which start
539 with ``(stmt, (compound_stmt, (classdef, ...`` or ``(stmt, (compound_stmt,
540 (funcdef, ...``. Note that these subtrees cannot be matched by :func:`match`
541 since it does not support multiple sibling nodes to match without regard to
542 number. A more elaborate matching function could be used to overcome this
543 limitation, but this is sufficient for the example.
545 Given the ability to determine whether a statement might be a docstring and
546 extract the actual string from the statement, some work needs to be performed to
547 walk the parse tree for an entire module and extract information about the names
548 defined in each context of the module and associate any docstrings with the
549 names. The code to perform this work is not complicated, but bears some
552 The public interface to the classes is straightforward and should probably be
553 somewhat more flexible. Each "major" block of the module is described by an
554 object providing several methods for inquiry and a constructor which accepts at
555 least the subtree of the complete parse tree which it represents. The
556 :class:`ModuleInfo` constructor accepts an optional *name* parameter since it
557 cannot otherwise determine the name of the module.
559 The public classes include :class:`ClassInfo`, :class:`FunctionInfo`, and
560 :class:`ModuleInfo`. All objects provide the methods :meth:`get_name`,
561 :meth:`get_docstring`, :meth:`get_class_names`, and :meth:`get_class_info`. The
562 :class:`ClassInfo` objects support :meth:`get_method_names` and
563 :meth:`get_method_info` while the other classes provide
564 :meth:`get_function_names` and :meth:`get_function_info`.
566 Within each of the forms of code block that the public classes represent, most
567 of the required information is in the same form and is accessed in the same way,
568 with classes having the distinction that functions defined at the top level are
569 referred to as "methods." Since the difference in nomenclature reflects a real
570 semantic distinction from functions defined outside of a class, the
571 implementation needs to maintain the distinction. Hence, most of the
572 functionality of the public classes can be implemented in a common base class,
573 :class:`SuiteInfoBase`, with the accessors for function and method information
574 provided elsewhere. Note that there is only one class which represents function
575 and method information; this parallels the use of the :keyword:`def` statement
576 to define both types of elements.
578 Most of the accessor functions are declared in :class:`SuiteInfoBase` and do not
579 need to be overridden by subclasses. More importantly, the extraction of most
580 information from a parse tree is handled through a method called by the
581 :class:`SuiteInfoBase` constructor. The example code for most of the classes is
582 clear when read alongside the formal grammar, but the method which recursively
583 creates new information objects requires further examination. Here is the
584 relevant part of the :class:`SuiteInfoBase` definition from :file:`example.py`::
590 def __init__(self, tree = None):
591 self._class_info = {}
592 self._function_info = {}
594 self._extract_info(tree)
596 def _extract_info(self, tree):
599 found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
601 found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
603 self._docstring = eval(vars['docstring'])
604 # discover inner definitions
605 for node in tree[1:]:
606 found, vars = match(COMPOUND_STMT_PATTERN, node)
608 cstmt = vars['compound']
609 if cstmt[0] == symbol.funcdef:
611 self._function_info[name] = FunctionInfo(cstmt)
612 elif cstmt[0] == symbol.classdef:
614 self._class_info[name] = ClassInfo(cstmt)
616 After initializing some internal state, the constructor calls the
617 :meth:`_extract_info` method. This method performs the bulk of the information
618 extraction which takes place in the entire example. The extraction has two
619 distinct phases: the location of the docstring for the parse tree passed in, and
620 the discovery of additional definitions within the code block represented by the
623 The initial :keyword:`if` test determines whether the nested suite is of the
624 "short form" or the "long form." The short form is used when the code block is
625 on the same line as the definition of the code block, as in ::
627 def square(x): "Square an argument."; return x ** 2
629 while the long form uses an indented block and allows nested definitions::
632 "Make a function that raises an argument to the exponent `exp'."
633 def raiser(x, y=exp):
637 When the short form is used, the code block may contain a docstring as the
638 first, and possibly only, :const:`small_stmt` element. The extraction of such a
639 docstring is slightly different and requires only a portion of the complete
640 pattern used in the more common case. As implemented, the docstring will only
641 be found if there is only one :const:`small_stmt` node in the
642 :const:`simple_stmt` node. Since most functions and methods which use the short
643 form do not provide a docstring, this may be considered sufficient. The
644 extraction of the docstring proceeds using the :func:`match` function as
645 described above, and the value of the docstring is stored as an attribute of the
646 :class:`SuiteInfoBase` object.
648 After docstring extraction, a simple definition discovery algorithm operates on
649 the :const:`stmt` nodes of the :const:`suite` node. The special case of the
650 short form is not tested; since there are no :const:`stmt` nodes in the short
651 form, the algorithm will silently skip the single :const:`simple_stmt` node and
652 correctly not discover any nested definitions.
654 Each statement in the code block is categorized as a class definition, function
655 or method definition, or something else. For the definition statements, the
656 name of the element defined is extracted and a representation object appropriate
657 to the definition is created with the defining subtree passed as an argument to
658 the constructor. The representation objects are stored in instance variables
659 and may be retrieved by name using the appropriate accessor methods.
661 The public classes provide any accessors required which are more specific than
662 those provided by the :class:`SuiteInfoBase` class, but the real extraction
663 algorithm remains common to all forms of code blocks. A high-level function can
664 be used to extract the complete set of information from a source file. (See
665 file :file:`example.py`.) ::
667 def get_docs(fileName):
671 source = open(fileName).read()
672 basename = os.path.basename(os.path.splitext(fileName)[0])
673 ast = parser.suite(source)
674 return ModuleInfo(ast.totuple(), basename)
676 This provides an easy-to-use interface to the documentation of a module. If
677 information is required which is not extracted by the code of this example, the
678 code may be extended at clearly defined points to provide additional