Python Abstract Syntax Tree New Generation

The aim of this module is to provide a common base representation of python source code for projects such as pychecker, pyreverse, pylint… Well, actually the development of this library is essentially governed by pylint’s needs.

It extends class defined in the python’s _ast module with some additional methods and attributes. Instance attributes are added by a builder object, which can either generate extended ast (let’s call them astroid ;) by visiting an existent ast tree or by inspecting living object. Methods are added by monkey patching ast classes.

Main modules are:

  • nodes and scoped_nodes for more information about methods and attributes added to different node classes
  • the manager contains a high level object to get astroid trees from source files and living objects. It maintains a cache of previously constructed tree for quick access
  • builder contains the class responsible to build astroid trees
class astroid.AsStringRegexpPredicate(regexp, expression=None)[source]

Bases: object

ClassDef to be used as predicate that may be given to register_transform

First argument is a regular expression that will be searched against the as_string representation of the node onto which it’s applied.

If specified, the second argument is an attrgetter expression that will be applied on the node first to get the actual node on which as_string should be called.

WARNING: This can be fairly slow, as it has to convert every AST node back to Python code; you should consider examining the AST directly instead.

astroid.inference_tip(infer_function, raise_on_overwrite=False)[source]

Given an instance specific inference function, return a function to be given to MANAGER.register_transform to set this inference function.

Parameters:raise_on_overwrite (bool) – Raise an InferenceOverwriteError if the inference tip will overwrite another. Used for debugging

Typical usage

MANAGER.register_transform(Call, inference_tip(infer_named_tuple),


Using an inference tip will override any previously set inference tip for the given node. Use a predicate in the transform to prevent excess overwrites.

astroid.register_module_extender(manager, module_name, get_extension_mod)[source]


astroid.exceptions this module contains exceptions used in the astroid library
astroid.nodes Every available node class.


AstroidBuildingError([message]) exception class when we are unable to build an astroid representation
AstroidBuildingException alias of AstroidBuildingError
AstroidError([message]) base exception class for all astroid related exceptions
AstroidImportError([message]) Exception class used when a module can’t be imported by astroid.
AstroidIndexError([message]) Raised when an Indexable / Mapping does not have an index / key.
AstroidSyntaxError([message]) Exception class used when a module can’t be parsed.
AstroidTypeError([message]) Raised when a TypeError would be expected in Python code.
AttributeInferenceError([message]) Raised when an attribute lookup fails, corresponds to AttributeError.
BinaryOperationError alias of BadBinaryOperationMessage
DuplicateBasesError([message]) Error raised when there are duplicate bases in the same class bases.
InconsistentMroError([message]) Error raised when a class’s MRO is inconsistent.
InferenceError([message]) raised when we are unable to infer a node
MroError([message]) Error raised when there is a problem with method resolution of a class.
NameInferenceError([message]) Raised when a name lookup fails, corresponds to NameError.
NoDefault([message]) raised by function’s default_value method when an argument has
NotFoundError alias of AttributeInferenceError
OperationError alias of BadOperationMessage
ResolveError([message]) Base class of astroid resolution/inference error.
SuperArgumentTypeError alias of SuperError
SuperError([message]) Error raised when there is a problem with a super call.
TooManyLevelsError([message]) Exception class which is raised when a relative import was beyond the top-level.
UnaryOperationError alias of BadUnaryOperationMessage
UnresolvableName alias of NameInferenceError
UseInferenceDefault exception to be raised in custom inference function to indicate that it

The manager for doing stuff.

astroid.are_exclusive(stmt1, stmt2, exceptions=None)[source]

return true if the two given statements are mutually exclusive

exceptions may be a list of exception names. If specified, discard If branches and check one of the statement is in an exception handler catching one of the given exceptions.

algorithm :
  1. index stmt1’s parents
  2. climb among stmt2’s parents until we find a common parent
  3. if the common parent is a If or TryExcept statement, look if nodes are in exclusive branches

lookup a name into the builtin module return the list of matching statements and the astroid for the builtin module

astroid.extract_node(code, module_name='')[source]

Parses some Python code as a module and extracts a designated AST node.


To extract one or more statement nodes, append #@ to the end of the line

>>> def x():
>>>   def y():
>>>     return 1 #@

The return statement will be extracted.

>>> class X(object):
>>>   def meth(self): #@
>>>     pass

The function object ‘meth’ will be extracted.


To extract arbitrary expressions, surround them with the fake function call __(…). After parsing, the surrounded expression will be returned and the whole AST (accessible via the returned node’s parent attribute) will look like the function call was never there in the first place.

>>> a = __(1)

The const node will be extracted.

>>> def x(d=__( pass

The node containing the default argument will be extracted.

>>> def foo(a, b):
>>>   return 0 < __(len(a)) < b

The node containing the function call ‘len’ will be extracted.

If no statements or expressions are selected, the last toplevel statement will be returned.

If the selected statement is a discard statement, (i.e. an expression turned into a statement), the wrapped expression is returned instead.

For convenience, singleton lists are unpacked.

Parameters:code (str) – A piece of Python code that is parsed as

a module. Will be passed through textwrap.dedent first. :param str module_name: The name of the module. :returns: The designated node from the parse tree, or a list of nodes. :rtype: astroid.bases.NodeNG, or a list of nodes.

astroid.parse(code, module_name='', path=None, apply_transforms=True)[source]

Parses a source string in order to obtain an astroid AST from it

  • code (str) – The code for the module.
  • module_name (str) – The name for the module, if any
  • path (str) – The path for the module
  • apply_transforms (bool) – Apply the transforms for the give code. Use it if you don’t want the default transforms to be applied.
astroid.unpack_infer(stmt, context=None)[source]

recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements