General API

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 mimics the class defined in the python’s _ast module with some additional methods and attributes. New nodes instances are not fully compatible with python’s _ast.

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.

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.BaseInstance(proxied: ClassDef | FunctionDef | Lambda | UnboundMethod | None = None)[source]

Bases: Proxy

An instance base class, which provides lookup methods for potential instances.

display_type() str[source]
getattr(name: str, context: InferenceContext | None = None, lookupclass: bool = True) list[InferenceResult][source]
igetattr(name: str, context: InferenceContext | None = None) Iterator[InferenceResult][source]

Inferred getattr.

infer_call_result(caller: SuccessfulInferenceResult | None, context: InferenceContext | None = None) Iterator[InferenceResult][source]

Infer what a class instance is returning when called.

special_attributes: ObjectModel
class astroid.BoundMethod(proxy: nodes.FunctionDef | nodes.Lambda | UnboundMethod, bound: SuccessfulInferenceResult, original_caller: SuccessfulInferenceResult | None = None)[source]

Bases: UnboundMethod

A special node representing a method bound to an instance.

bool_value(context: InferenceContext | None = None) Literal[True][source]
implicit_parameters() Literal[0, 1][source]
infer_call_result(caller: SuccessfulInferenceResult | None, context: InferenceContext | None = None) Iterator[InferenceResult][source]

The boundnode of the regular context with a function called on object.__new__ will be of type object, which is incorrect for the argument in general. If no context is given the object.__new__ call argument will be correctly inferred except when inside a call that requires the additional context (such as a classmethod) of the boundnode to determine which class the method was called from

is_bound() Literal[True][source]
special_attributes: BoundMethodModel | UnboundMethodModel
class astroid.Context(*values)[source]

Bases: Enum

Del = 3
Load = 1
Store = 2
class astroid.ExceptionInstance(proxied: ClassDef | None)[source]

Bases: Instance

Class for instances of exceptions.

It has special treatment for some of the exceptions’s attributes, which are transformed at runtime into certain concrete objects, such as the case of .args.

property special_attributes[source]
class astroid.Instance(proxied: ClassDef | None)[source]

Bases: BaseInstance

A special node representing a class instance.

bool_value(context: InferenceContext | None = None) bool | UninferableBase[source]

Infer the truth value for an Instance.

The truth value of an instance is determined by these conditions:

  • if it implements __bool__, then its bool value will be determined by calling this special method and checking its result.

  • when this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

callable() bool[source]
display_type() str[source]
getitem(index: nodes.Const, context: InferenceContext | None = None) InferenceResult | None[source]
infer_binary_op(**kwargs: _P.kwargs) Generator[InferenceResult]
pytype() str[source]
special_attributes: ObjectModel
class astroid.UnboundMethod(proxied: ClassDef | FunctionDef | Lambda | UnboundMethod | None = None)[source]

Bases: Proxy

A special node representing a method not bound to an instance.

bool_value(context: InferenceContext | None = None) Literal[True][source]
getattr(name: str, context: InferenceContext | None = None)[source]
igetattr(name: str, context: InferenceContext | None = None) Iterator[InferenceResult][source]
implicit_parameters() Literal[0, 1][source]
infer_call_result(caller: SuccessfulInferenceResult | None, context: InferenceContext | None = None) Iterator[InferenceResult][source]

The boundnode of the regular context with a function called on object.__new__ will be of type object, which is incorrect for the argument in general. If no context is given the object.__new__ call argument will be correctly inferred except when inside a call that requires the additional context (such as a classmethod) of the boundnode to determine which class the method was called from

is_bound() bool[source]
special_attributes: BoundMethodModel | UnboundMethodModel
astroid.are_exclusive(stmt1, stmt2, exceptions: list[str] | None = None) bool[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 Try statement, look if nodes are in exclusive branches

astroid.builtin_lookup(name: str) tuple[nodes.Module, list[nodes.NodeNG]][source]

Lookup a name in the builtin module.

Return the list of matching statements and the ast for the builtin module

astroid.extract_node(code: str, module_name: str = '') NodeNG | list[NodeNG][source]

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

Statements:

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

Examples:

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.

Expressions:

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.

Examples:

a = __(1)

The const node will be extracted.

def x(d=__(foo.bar)): 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.

  • module_name (str) – The name of the module.

Returns:

The designated node from the parse tree, or a list of nodes.

astroid.function_to_method(n, klass)[source]
astroid.inference_tip(infer_function: InferFn[_NodesT], raise_on_overwrite: bool = False) TransformFn[_NodesT][source]

Given an instance specific inference function, return a function to be given to AstroidManager().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

AstroidManager().register_transform(Call, inference_tip(infer_named_tuple),
                           predicate)

Note

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.parse(code: str, module_name: str = '', path: str | None = None, apply_transforms: bool = True) Module[source]

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

Parameters:
  • 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.register_module_extender(manager: AstroidManager, module_name: str, get_extension_mod: Callable[[], Module]) None[source]
astroid.unpack_infer(*args: _P.args, **kwargs: _P.kwargs) Generator[InferenceResult]
astroid.Uninferable

Special inference object, which is returned when inference fails.

This is meant to be used as a singleton. Use astroid.util.Uninferable to access it.