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
- exception astroid.AstroidBuildingError(message: str = 'Failed to import module {modname}.', modname: str | None = None, error: Exception | None = None, source: str | None = None, path: str | None = None, cls: type | None = None, class_repr: str | None = None, **kws: Any)[source]¶
Bases:
AstroidErrorException class when we are unable to build an astroid representation.
- Standard attributes:
modname: Name of the module that AST construction failed for. error: Exception raised during construction.
- exception astroid.AstroidError(message: str = '', **kws: Any)[source]¶
Bases:
ExceptionBase exception class for all astroid related exceptions.
AstroidError and its subclasses are structured, intended to hold objects representing state when the exception is thrown. Field values are passed to the constructor as keyword-only arguments. Each subclass has its own set of standard fields, but use your best judgment to decide whether a specific exception instance needs more or fewer fields for debugging. Field values may be used to lazily generate the error message: self.message.format() will be called with the field names and values supplied as keyword arguments.
- exception astroid.AstroidImportError(message: str = 'Failed to import module {modname}.', modname: str | None = None, error: Exception | None = None, source: str | None = None, path: str | None = None, cls: type | None = None, class_repr: str | None = None, **kws: Any)[source]¶
Bases:
AstroidBuildingErrorException class used when a module can’t be imported by astroid.
- exception astroid.AstroidIndexError(message: str = '', node: nodes.NodeNG | bases.Instance | None = None, index: nodes.Subscript | None = None, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
AstroidErrorRaised when an Indexable / Mapping does not have an index / key.
- exception astroid.AstroidSyntaxError(message: str, modname: str | None, error: Exception, path: str | None, source: str | None = None)[source]¶
Bases:
AstroidBuildingErrorException class used when a module can’t be parsed.
- exception astroid.AstroidTypeError(message: str = '', node: nodes.NodeNG | bases.Instance | None = None, index: nodes.Subscript | None = None, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
AstroidErrorRaised when a TypeError would be expected in Python code.
- exception astroid.AstroidValueError(message: str = '', **kws: Any)[source]¶
Bases:
AstroidErrorRaised when a ValueError would be expected in Python code.
- exception astroid.AttributeInferenceError(message: str = '{attribute!r} not found on {target!r}.', attribute: str = '', target: nodes.NodeNG | bases.BaseInstance | None = None, context: InferenceContext | None = None, mros: list[nodes.ClassDef] | None = None, super_: nodes.ClassDef | None = None, cls: nodes.ClassDef | None = None, **kws: Any)[source]¶
Bases:
ResolveErrorRaised when an attribute lookup fails, corresponds to AttributeError.
- Standard attributes:
target: The node for which lookup failed. attribute: The attribute for which lookup failed, as a string. context: InferenceContext object.
- class astroid.BaseInstance(proxied: ClassDef | FunctionDef | Lambda | UnboundMethod | None = None)[source]¶
Bases:
ProxyAn instance base class, which provides lookup methods for potential instances.
- 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:
UnboundMethodA special node representing a method bound to an instance.
- 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 typeobject, which is incorrect for the argument in general. If no context is given theobject.__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
- special_attributes: BoundMethodModel | UnboundMethodModel¶
- exception astroid.DuplicateBasesError(message: str, mros: Iterable[Iterable[nodes.ClassDef]], cls: nodes.ClassDef, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
MroErrorError raised when there are duplicate bases in the same class bases.
- class astroid.ExceptionInstance(proxied: ClassDef | None)[source]¶
Bases:
InstanceClass 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¶
- exception astroid.InconsistentMroError(message: str, mros: Iterable[Iterable[nodes.ClassDef]], cls: nodes.ClassDef, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
MroErrorError raised when a class’s MRO is inconsistent.
- exception astroid.InferenceError(message: str = 'Inference failed for {node!r}.', node: InferenceResult | None = None, context: InferenceContext | None = None, target: InferenceResult | None = None, targets: InferenceResult | None = None, attribute: str | None = None, unknown: InferenceResult | None = None, assign_path: list[int] | None = None, caller: SuccessfulInferenceResult | None = None, stmts: Iterator[InferenceResult] | None = None, frame: InferenceResult | None = None, call_site: arguments.CallSite | None = None, func: InferenceResult | None = None, arg: str | None = None, positional_arguments: list | None = None, unpacked_args: list | None = None, keyword_arguments: dict | None = None, unpacked_kwargs: dict | None = None, **kws: Any)[source]¶
Bases:
ResolveErrorRaised when we are unable to infer a node.
- Standard attributes:
node: The node inference was called on. context: InferenceContext object.
- exception astroid.InferenceOverwriteError(message: str = '', **kws: Any)[source]¶
Bases:
AstroidErrorRaised when an inference tip is overwritten.
Currently only used for debugging.
- class astroid.Instance(proxied: ClassDef | None)[source]¶
Bases:
BaseInstanceA 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__ on Python 3 or __nonzero__ on Python 2, 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.
- getitem(index: nodes.Const, context: InferenceContext | None = None) InferenceResult | None[source]¶
- infer_binary_op(**kwargs: _P.kwargs) Generator[InferenceResult]¶
- special_attributes: ObjectModel¶
- exception astroid.MroError(message: str, mros: Iterable[Iterable[nodes.ClassDef]], cls: nodes.ClassDef, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
ResolveErrorError raised when there is a problem with method resolution of a class.
- Standard attributes:
mros: A sequence of sequences containing ClassDef nodes. cls: ClassDef node whose MRO resolution failed. context: InferenceContext object.
- exception astroid.NameInferenceError(message: str = '{name!r} not found in {scope!r}.', name: str | None = None, scope: nodes.LocalsDictNodeNG | None = None, context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
InferenceErrorRaised when a name lookup fails, corresponds to NameError.
- Standard attributes:
name: The name for which lookup failed, as a string. scope: The node representing the scope in which the lookup occurred. context: InferenceContext object.
- exception astroid.NoDefault(message: str = '{func!r} has no default for {name!r}.', func: nodes.FunctionDef | None = None, name: str | None = None, **kws: Any)[source]¶
Bases:
AstroidErrorRaised by function’s default_value method when an argument has no default value.
- Standard attributes:
func: Function node. name: Name of argument without a default.
- astroid.NotFoundError¶
alias of
AttributeInferenceError
- exception astroid.ParentMissingError(target: nodes.NodeNG)[source]¶
Bases:
AstroidErrorRaised when a node which is expected to have a parent attribute is missing one.
- Standard attributes:
target: The node for which the parent lookup failed.
- exception astroid.ResolveError(message: str = '', context: InferenceContext | None = None, **kws: Any)[source]¶
Bases:
AstroidErrorBase class of astroid resolution/inference error.
ResolveError is not intended to be raised.
- Standard attributes:
context: InferenceContext object.
- exception astroid.StatementMissing(target: nodes.NodeNG)[source]¶
Bases:
ParentMissingErrorRaised when a call to node.statement() does not return a node.
This is because a node in the chain does not have a parent attribute and therefore does not return a node for statement().
- Standard attributes:
target: The node for which the parent lookup failed.
- astroid.SuperArgumentTypeError¶
alias of
SuperError
- exception astroid.SuperError(message: str, super_: objects.Super, **kws: Any)[source]¶
Bases:
ResolveErrorError raised when there is a problem with a super call.
- Standard attributes:
super_: The Super instance that raised the exception. context: InferenceContext object.
- exception astroid.TooManyLevelsError(message: str = 'Relative import with too many levels ({level}) for module {name!r}', level: int | None = None, name: str | None = None, **kws: Any)[source]¶
Bases:
AstroidImportErrorException class which is raised when a relative import was beyond the top-level.
- Standard attributes:
level: The level which was attempted. name: the name of the module on which the relative import was attempted.
- class astroid.UnboundMethod(proxied: ClassDef | FunctionDef | Lambda | UnboundMethod | None = None)[source]¶
Bases:
ProxyA special node representing a method not bound to an instance.
- 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 typeobject, which is incorrect for the argument in general. If no context is given theobject.__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
- special_attributes: BoundMethodModel | UnboundMethodModel¶
- astroid.UnresolvableName¶
alias of
NameInferenceError
- exception astroid.UseInferenceDefault[source]¶
Bases:
ExceptionException to be raised in custom inference function to indicate that it should go back to the default behaviour.
- 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 :
index stmt1’s parents
climb among stmt2’s parents until we find a common parent
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. :param str module_name: The name of the module. :returns: The designated node from the parse tree, or a list of nodes.
- 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.
- 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]¶