class documentation

class SemanticAnalyzer(NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface): (source)

View In Hierarchy

Semantically analyze parsed mypy files.

The analyzer binds names and does various consistency checks for an AST. Note that type checking is performed as a separate pass.

Method __init__ Construct semantic analyzer.
Method accept Undocumented
Method add​_builtin​_aliases Add builtin type aliases to typing module.
Method add​_exports Undocumented
Method add​_function​_to​_symbol​_table Undocumented
Method add​_implicit​_module​_attrs Manually add implicit definitions of module '__name__' etc.
Method add​_imported​_symbol Add an alias to an existing symbol through import.
Method add​_local Add local variable or function.
Method add​_module​_symbol Add symbol that is a reference to a module object.
Method add​_plugin​_dependency Add dependency from trigger to a target.
Method add​_redefinition Add a symbol table node that reflects a redefinition as a function or a class.
Method add​_symbol Add symbol to the currently active symbol table.
Method add​_symbol​_skip​_local Same as above, but skipping the local namespace.
Method add​_symbol​_table​_node Add symbol table node to the currently active symbol table.
Method add​_type​_alias​_deps Add full names of type aliases on which the current node depends.
Method add​_typing​_extension​_aliases Typing extensions module does contain some type aliases.
Method add​_unknown​_imported​_symbol Add symbol that we don't know what it points to because resolving an import failed.
Method adjust​_public​_exports Adjust the module visibility of globals due to __all__.
Method already​_defined Undocumented
Method anal​_type Semantically analyze a type.
Method analyze​_alias Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable).
Method analyze​_arg​_initializers Undocumented
Method analyze​_base​_classes Analyze base class types.
Method analyze​_class Undocumented
Method analyze​_class​_body​_common Parts of class body analysis that are common to all kinds of class defs.
Method analyze​_class​_decorator Undocumented
Method analyze​_class​_keywords Undocumented
Method analyze​_class​_typevar​_declaration Analyze type variables declared using Generic[...] or Protocol[...].
Method analyze​_comp​_for Analyses the 'comp_for' part of comprehensions (part 1).
Method analyze​_comp​_for​_2 Analyses the 'comp_for' part of comprehensions (part 2).
Method analyze​_enum​_assign Check if s defines an Enum.
Method analyze​_func​_def Undocumented
Method analyze​_function​_body Undocumented
Method analyze​_identity​_global​_assignment Special case 'X = X' in global scope.
Method analyze​_lvalue Analyze an lvalue or assignment target.
Method analyze​_lvalues Undocumented
Method analyze​_member​_lvalue Analyze lvalue that is a member expression.
Method analyze​_metaclass Undocumented
Method analyze​_name​_lvalue Analyze an lvalue that targets a name expression.
Method analyze​_namedtuple​_assign Check if s defines a namedtuple.
Method analyze​_namedtuple​_classdef Check if this class can define a named tuple.
Method analyze​_overload​_sigs​_and​_impl Find overload signatures, the implementation, and items with missing @overload.
Method analyze​_overloaded​_func​_def Undocumented
Method analyze​_property​_with​_multi​_part​_definition Analyze a property defined using multiple methods (e.g., using @x.setter).
Method analyze​_simple​_literal​_type Return builtins.int if rvalue is an int literal, etc.
Method analyze​_try​_stmt Undocumented
Method analyze​_tuple​_or​_list​_lvalue Analyze an lvalue or assignment target that is a list or tuple.
Method analyze​_type​_application Analyze special form -- type application (either direct or via type aliasing).
Method analyze​_type​_application​_args Analyze type arguments (index) in a type application.
Method analyze​_type​_expr Undocumented
Method analyze​_typeddict​_assign Check if s defines a typed dict.
Method analyze​_unbound​_tvar Undocumented
Method analyze​_value​_types Analyze types from values expressions in type variable definition.
Method apply​_class​_plugin​_hooks Apply a plugin hook that may infer a more precise definition for a class.
Method apply​_dynamic​_class​_hook Undocumented
Method attribute​_already​_defined Undocumented
Method basic​_new​_typeinfo Undocumented
Method bind​_name​_expr Bind name expression to a symbol table node.
Method calculate​_class​_mro Calculate method resolution order for a class.
Method can​_be​_type​_alias Is this a valid r.h.s. for an alias definition?
Method cannot​_resolve​_name Undocumented
Method check​_and​_set​_up​_type​_alias Check if assignment creates a type alias and set it up as needed.
Method check​_classvar Check if assignment defines a class variable.
Method check​_classvar​_in​_signature Undocumented
Method check​_decorated​_function​_is​_method Undocumented
Method check​_final​_implicit​_def Do basic checks for final declaration on self in __init__.
Method check​_fixed​_args Verify that expr has specified number of positional args.
Method check​_function​_signature Undocumented
Method check​_lvalue​_validity Undocumented
Method check​_no​_global Undocumented
Method check​_typevarlike​_name Checks that the name of a TypeVar or ParamSpec matches its variable.
Method class​_type Generate type of first argument of class methods from type of self.
Method clean​_up​_bases​_and​_infer​_type​_variables Remove extra base classes such as Generic and infer type vars.
Method configure​_base​_classes Set up base classes.
Method configure​_tuple​_base​_class Undocumented
Method correct​_relative​_import Undocumented
Method create​_alias Undocumented
Method create​_getattr​_var Create a dummy variable using module-level __getattr__ return type.
Method current​_symbol​_kind Undocumented
Method current​_symbol​_table Get currently active symbol table.
Method defer Defer current analysis target to be analyzed again.
Method enter Enter a function, generator or comprehension scope.
Method enter​_class Undocumented
Method enum​_has​_final​_values Undocumented
Method expr​_to​_analyzed​_type Undocumented
Method expr​_to​_unanalyzed​_type Undocumented
Method fail Emit an error message at given location.
Method fail​_blocker Undocumented
Method fail​_invalid​_classvar Undocumented
Method file​_context Configure analyzer for analyzing targets within a file/class.
Method flatten​_lvalues Undocumented
Method found​_incomplete​_ref Have we encountered an incomplete reference since starting tracking?
Method get​_all​_bases​_tvars Return all type variable references in bases.
Method get​_module​_symbol Look up a symbol from a module.
Method get​_name​_repr​_of​_expr Try finding a short simplified textual representation of a base class expression.
Method get​_typevarlike​_declaration Returns the call expression if s is a declaration of typevarlike_type (TypeVar or ParamSpec), or None otherwise.
Method handle​_missing​_overload​_decorators Generate errors for overload items without @overload.
Method handle​_missing​_overload​_implementation Generate error about missing overload implementation (only if needed).
Method implicit​_symbol Create symbol for a qualified name reference through Any type.
Method in​_checked​_function Should we type-check the current function?
Method is​_active​_symbol​_in​_class​_body Can a symbol defined in class body accessed at current statement?
Method is​_alias​_for​_final​_name Undocumented
Method is​_annotated​_protocol​_member Check whether a protocol member is annotated.
Method is​_base​_class Determine if t is a base class of s (but do not use mro).
Method is​_class​_scope Undocumented
Method is​_classvar Undocumented
Method is​_core​_builtin​_class Undocumented
Method is​_defined​_in​_current​_module Undocumented
Method is​_final​_redefinition Undocumented
Method is​_final​_type Undocumented
Method is​_func​_scope Undocumented
Method is​_future​_flag​_set Is the specific __future__ feature imported
Method is​_global​_or​_nonlocal Undocumented
Method is​_incomplete​_namespace Is a module or class namespace potentially missing some definitions?
Method is​_initial​_mangled​_global Undocumented
Method is​_local​_name Does name look like reference to a definition in the current module?
Method is​_mangled​_global Undocumented
Method is​_missing​_module Undocumented
Method is​_module​_scope Undocumented
Method is​_nested​_within​_func​_scope Are we underneath a function scope, even if we are in a nested class also?
Method is​_none​_alias Is this a r.h.s. for a None alias?
Method is​_overloaded​_item Check whether the function belongs to the overloaded variants
Method is​_self​_member​_ref Does memberexpr to refer to an attribute of self?
Method is​_textually​_before​_statement Check if a node is defined textually before the current statement
Method is​_type​_ref Does this expression refer to a type?
Method is​_valid​_del​_target Undocumented
Method leave​_class Restore analyzer state.
Method lookup Look up an unqualified (no dots) name in all active namespaces.
Method lookup​_current​_scope Undocumented
Method lookup​_fully​_qualified Lookup a symbol by its fully qualified name.
Method lookup​_fully​_qualified​_or​_none Lookup a fully qualified name that refers to a module-level definition.
Method lookup​_qualified Lookup a qualified name in all activate namespaces.
Method lookup​_type​_node Undocumented
Method make​_empty​_type​_info Undocumented
Method make​_name​_lvalue​_point​_to​_existing​_def Update an lvalue to point to existing definition in the same scope.
Method make​_name​_lvalue​_var Return a Var node for an lvalue that is a name expression.
Method mark​_incomplete Mark a definition as incomplete (and defer current analysis target).
Method name​_already​_defined Undocumented
Method name​_not​_defined Undocumented
Method named​_type Construct an instance of a builtin type with given type arguments.
Method named​_type​_or​_none Construct an instance of a type with given type arguments.
Method note Undocumented
Method object​_type Undocumented
Method parse​_bool Parse True/False literals.
Method prepare​_builtins​_namespace Add certain special-cased definitions to the builtins module.
Method prepare​_class​_def Prepare for the analysis of a class definition.
Method prepare​_file Prepare a freshly parsed file for semantic analysis.
Method prepare​_method​_signature Check basic signature validity and tweak annotation of self/cls argument.
Method prepare​_typing​_namespace Remove dummy alias definitions such as List = TypeAlias(object) from typing.
Method process​_​_all__ Export names if argument is a __all__ assignment.
Method process​_​_deletable__ Undocumented
Method process​_​_slots__ Processing __slots__ if defined in type.
Method process​_final​_in​_overload Detect the @final status of an overloaded function (and perform checks).
Method process​_import​_over​_existing​_name Undocumented
Method process​_imported​_symbol Undocumented
Method process​_module​_assignment Propagate module references across assignments.
Method process​_paramspec​_declaration Checks if s declares a ParamSpec; if yes, store it in symbol table.
Method process​_placeholder Process a reference targeting placeholder node.
Method process​_static​_or​_class​_method​_in​_overload Undocumented
Method process​_type​_annotation Analyze type annotation or infer simple literal type.
Method process​_typevar​_declaration Check if s declares a TypeVar; it yes, store it in symbol table.
Method process​_typevar​_parameters Undocumented
Method qualified​_name Make qualified name using current module and enclosing class (if any).
Method record​_incomplete​_ref Record the encounter of an incomplete reference and defer current analysis target.
Method record​_special​_form​_lvalue Record minimal necessary information about l.h.s. of a special form.
Method refresh​_partial Refresh a stale target in fine-grained incremental mode.
Method refresh​_top​_level Reanalyze a stale module top-level in fine-grained incremental mode.
Method report​_hang Undocumented
Method report​_missing​_module​_attribute Undocumented
Method schedule​_patch Undocumented
Method set​_dummy​_mro Undocumented
Method set​_future​_import​_flags Undocumented
Method set​_original​_def If 'new' conditionally redefine 'previous', set 'previous' as original
Method should​_wait​_rhs Can we already classify this r.h.s. of an assignment or should we wait?
Method store​_declared​_types Undocumented
Method store​_final​_status If this is a locally valid final declaration, set the corresponding flag on Var.
Method str​_type Undocumented
Method track​_incomplete​_refs Return tag that can be used for tracking references to incomplete names.
Method translate​_dict​_call Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}.
Method tvar​_scope​_frame Undocumented
Method type​_analyzer Undocumented
Method unbox​_literal Undocumented
Method unwrap​_final Strip Final[...] if present in an assignment.
Method update​_function​_type​_variables Make any type variables in the signature of defn explicit.
Method update​_metaclass Lookup for special metaclass declarations, and update defn fields accordingly.
Method verify​_base​_classes Undocumented
Method visit​_​_promote​_expr Undocumented
Method visit​_assert​_stmt Undocumented
Method visit​_assignment​_expr Undocumented
Method visit​_assignment​_stmt Undocumented
Method visit​_await​_expr Undocumented
Method visit​_backquote​_expr Undocumented
Method visit​_block Undocumented
Method visit​_block​_maybe Undocumented
Method visit​_break​_stmt Undocumented
Method visit​_call​_expr Analyze a call expression.
Method visit​_cast​_expr Undocumented
Method visit​_class​_def Undocumented
Method visit​_comparison​_expr Undocumented
Method visit​_conditional​_expr Undocumented
Method visit​_continue​_stmt Undocumented
Method visit​_decorator Undocumented
Method visit​_del​_stmt Undocumented
Method visit​_dict​_expr Undocumented
Method visit​_dictionary​_comprehension Undocumented
Method visit​_exec​_stmt Undocumented
Method visit​_expression​_stmt Undocumented
Method visit​_for​_stmt Undocumented
Method visit​_func​_def Undocumented
Method visit​_generator​_expr Undocumented
Method visit​_global​_decl Undocumented
Method visit​_if​_stmt Undocumented
Method visit​_import Undocumented
Method visit​_import​_all Undocumented
Method visit​_import​_from Undocumented
Method visit​_index​_expr Undocumented
Method visit​_lambda​_expr Undocumented
Method visit​_list​_comprehension Undocumented
Method visit​_list​_expr Undocumented
Method visit​_member​_expr Undocumented
Method visit​_name​_expr Undocumented
Method visit​_nonlocal​_decl Undocumented
Method visit​_op​_expr Undocumented
Method visit​_operator​_assignment​_stmt Undocumented
Method visit​_overloaded​_func​_def Undocumented
Method visit​_print​_stmt Undocumented
Method visit​_raise​_stmt Undocumented
Method visit​_return​_stmt Undocumented
Method visit​_reveal​_expr Undocumented
Method visit​_set​_comprehension Undocumented
Method visit​_set​_expr Undocumented
Method visit​_slice​_expr Undocumented
Method visit​_star​_expr Undocumented
Method visit​_super​_expr Undocumented
Method visit​_try​_stmt Undocumented
Method visit​_tuple​_expr Undocumented
Method visit​_type​_application Undocumented
Method visit​_unary​_expr Undocumented
Method visit​_while​_stmt Undocumented
Method visit​_with​_stmt Undocumented
Method visit​_yield​_expr Undocumented
Method visit​_yield​_from​_expr Undocumented
Class Variable __deletable__ Undocumented
Class Variable global​_decls Undocumented
Class Variable nonlocal​_decls Undocumented
Class Variable progress Undocumented
Class Variable wrapped​_coro​_return​_types Undocumented
Instance Variable all​_exports Undocumented
Instance Variable block​_depth Undocumented
Instance Variable cur​_mod​_id Undocumented
Instance Variable cur​_mod​_node Undocumented
Instance Variable deferral​_debug​_context Undocumented
Instance Variable deferred Undocumented
Instance Variable enum​_call​_analyzer Undocumented
Instance Variable errors Undocumented
Instance Variable export​_map Undocumented
Instance Variable function​_stack Undocumented
Instance Variable future​_import​_flags Undocumented
Instance Variable globals Undocumented
Instance Variable imports Undocumented
Instance Variable incomplete Undocumented
Instance Variable incomplete​_namespaces Undocumented
Instance Variable incomplete​_type​_stack Undocumented
Instance Variable is​_comprehension​_stack Undocumented
Instance Variable locals Undocumented
Instance Variable loop​_depth Undocumented
Instance Variable missing​_modules Undocumented
Instance Variable missing​_names Undocumented
Instance Variable modules Undocumented
Instance Variable msg Undocumented
Instance Variable named​_tuple​_analyzer Undocumented
Instance Variable newtype​_analyzer Undocumented
Instance Variable num​_incomplete​_refs Undocumented
Instance Variable options Undocumented
Instance Variable patches Undocumented
Instance Variable plugin Undocumented
Instance Variable recurse​_into​_functions Undocumented
Instance Variable saved​_locals Undocumented
Instance Variable scope Undocumented
Instance Variable statement Undocumented
Instance Variable tvar​_scope Undocumented
Instance Variable type Undocumented
Instance Variable type​_stack Undocumented
Instance Variable typed​_dict​_analyzer Undocumented
Property final​_iteration Is this the final iteration of semantic analysis?
Property is​_stub​_file Undocumented
Property is​_typeshed​_stub​_file Undocumented
Instance Variable _final​_iteration Undocumented
Instance Variable _is​_stub​_file Undocumented
Instance Variable _is​_typeshed​_stub​_file Undocumented
def __init__(self, modules, missing_modules, incomplete_namespaces, errors, plugin): (source)

Construct semantic analyzer.

We reuse the same semantic analyzer instance across multiple modules.

Args:

modules: Global modules dictionary missing_modules: Modules that could not be imported encountered so far incomplete_namespaces: Namespaces that are being populated during semantic analysis

(can contain modules and classes within the current SCC; mutated by the caller)

errors: Report analysis errors using this instance

Parameters
modules:Dict[str, MypyFile]Undocumented
missing​_modules:Set[str]Undocumented
incomplete​_namespaces:Set[str]Undocumented
errors:ErrorsUndocumented
plugin:PluginUndocumented
def accept(self, node): (source)

Undocumented

Parameters
node:NodeUndocumented
def add_builtin_aliases(self, tree): (source)

Add builtin type aliases to typing module.

For historical reasons, the aliases like List = list are not defined in typeshed stubs for typing module. Instead we need to manually add the corresponding nodes on the fly. We explicitly mark these aliases as normalized, so that a user can write typing.List[int].

Parameters
tree:MypyFileUndocumented
def add_exports(self, exp_or_exps): (source)

Undocumented

Parameters
exp​_or​_exps:Union[Iterable[Expression], Expression]Undocumented
def add_function_to_symbol_table(self, func): (source)

Undocumented

Parameters
func:Union[FuncDef, OverloadedFuncDef]Undocumented
def add_implicit_module_attrs(self, file_node): (source)
Manually add implicit definitions of module '__name__' etc.
Parameters
file​_node:MypyFileUndocumented
def add_imported_symbol(self, name, node, context, module_public, module_hidden): (source)
Add an alias to an existing symbol through import.
Parameters
name:strUndocumented
node:SymbolTableNodeUndocumented
context:ContextUndocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
def add_local(self, node, context): (source)
Add local variable or function.
Parameters
node:Union[Var, FuncDef, OverloadedFuncDef]Undocumented
context:ContextUndocumented
def add_module_symbol(self, id, as_id, context, module_public, module_hidden): (source)
Add symbol that is a reference to a module object.
Parameters
id:strUndocumented
as​_id:strUndocumented
context:ContextUndocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
def add_plugin_dependency(self, trigger, target=None): (source)

Add dependency from trigger to a target.

If the target is not given explicitly, use the current target.

Parameters
trigger:strUndocumented
target:Optional[str]Undocumented
def add_redefinition(self, names, name, symbol): (source)

Add a symbol table node that reflects a redefinition as a function or a class.

Redefinitions need to be added to the symbol table so that they can be found through AST traversal, but they have dummy names of form 'name-redefinition[N]', where N ranges over 2, 3, ... (omitted for the first redefinition).

Note: we always store redefinitions independently of whether they are valid or not (so they will be semantically analyzed), the caller should give an error for invalid redefinitions (such as e.g. variable redefined as a class).

Parameters
names:SymbolTableUndocumented
name:strUndocumented
symbol:SymbolTableNodeUndocumented
def add_symbol(self, name, node, context, module_public=True, module_hidden=False, can_defer=True, escape_comprehensions=False): (source)

Add symbol to the currently active symbol table.

Generally additions to symbol table should go through this method or one of the methods below so that kinds, redefinitions, conditional definitions, and skipped names are handled consistently.

Return True if we actually added the symbol, or False if we refused to do so (because something is not ready).

If can_defer is True, defer current target if adding a placeholder.

Parameters
name:strUndocumented
node:SymbolNodeUndocumented
context:ContextUndocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
can​_defer:boolUndocumented
escape​_comprehensions:boolUndocumented
Returns
boolUndocumented
def add_symbol_skip_local(self, name, node): (source)

Same as above, but skipping the local namespace.

This doesn't check for previous definition and is only used for serialization of method-level classes.

Classes defined within methods can be exposed through an attribute type, but method-level symbol tables aren't serialized. This method can be used to add such classes to an enclosing, serialized symbol table.

Parameters
name:strUndocumented
node:SymbolNodeUndocumented
def add_symbol_table_node(self, name, symbol, context=None, can_defer=True, escape_comprehensions=False): (source)

Add symbol table node to the currently active symbol table.

Return True if we actually added the symbol, or False if we refused to do so (because something is not ready or it was a no-op).

Generate an error if there is an invalid redefinition.

If context is None, unconditionally add node, since we can't report an error. Note that this is used by plugins to forcibly replace nodes!

TODO: Prevent plugins from replacing nodes, as it could cause problems?

Args:
name: short name of symbol symbol: Node to add can_defer: if True, defer current target if adding a placeholder context: error context (see above about None value)
Parameters
name:strUndocumented
symbol:SymbolTableNodeUndocumented
context:Optional[Context]Undocumented
can​_defer:boolUndocumented
escape​_comprehensions:boolUndocumented
Returns
boolUndocumented
def add_type_alias_deps(self, aliases_used, target=None): (source)

Add full names of type aliases on which the current node depends.

This is used by fine-grained incremental mode to re-check the corresponding nodes. If target is None, then the target node used will be the current scope.

Parameters
aliases​_used:Iterable[str]Undocumented
target:Optional[str]Undocumented
def add_typing_extension_aliases(self, tree): (source)

Typing extensions module does contain some type aliases.

We need to analyze them as such, because in typeshed they are just defined as _Alias() call. Which is not supported natively.

Parameters
tree:MypyFileUndocumented
def add_unknown_imported_symbol(self, name, context, target_name, module_public, module_hidden): (source)

Add symbol that we don't know what it points to because resolving an import failed.

This can happen if a module is missing, or it is present, but doesn't have the imported attribute. The target_name is the name of symbol in the namespace it is imported from. For example, for 'from mod import x as y' the target_name is 'mod.x'. This is currently used only to track logical dependencies.

Parameters
name:strUndocumented
context:ContextUndocumented
target​_name:Optional[str]Undocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
def adjust_public_exports(self): (source)
Adjust the module visibility of globals due to __all__.
def already_defined(self, name, ctx, original_ctx, noun): (source)

Undocumented

Parameters
name:strUndocumented
ctx:ContextUndocumented
original​_ctx:Optional[Union[SymbolTableNode, SymbolNode]]Undocumented
noun:strUndocumented
def anal_type(self, typ, *, tvar_scope=None, allow_tuple_literal=False, allow_unbound_tvars=False, allow_placeholder=False, allow_required=False, report_invalid_types=True, third_pass=False): (source)

Semantically analyze a type.

Args:

typ: Type to analyze (if already analyzed, this is a no-op) allow_placeholder: If True, may return PlaceholderType if

encountering an incomplete definition
third_pass: Unused; only for compatibility with old semantic
analyzer

Return None only if some part of the type couldn't be bound and it referred to an incomplete namespace or definition. In this case also defer as needed. During a final iteration this won't return None; instead report an error if the type can't be analyzed and return AnyType.

In case of other errors, report an error message and return AnyType.

NOTE: The caller shouldn't defer even if this returns None or a
placeholder type.
Parameters
typ:TypeUndocumented
tvar​_scope:Optional[TypeVarLikeScope]Undocumented
allow​_tuple​_literal:boolUndocumented
allow​_unbound​_tvars:boolUndocumented
allow​_placeholder:boolUndocumented
allow​_required:boolUndocumented
report​_invalid​_types:boolUndocumented
third​_pass:boolUndocumented
Returns
Optional[Type]Undocumented
def analyze_alias(self, rvalue, allow_placeholder=False): (source)

Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable).

If yes, return the corresponding type, a list of qualified type variable names for generic aliases, a set of names the alias depends on, and a list of type variables if the alias is generic. An schematic example for the dependencies:

A = int B = str analyze_alias(Dict[A, B])[2] == {'__main__.A', '__main__.B'}
Parameters
rvalue:ExpressionUndocumented
allow​_placeholder:boolUndocumented
Returns
Tuple[Optional[Type], List[str], Set[str], List[str]]Undocumented
def analyze_arg_initializers(self, defn): (source)

Undocumented

Parameters
defn:FuncItemUndocumented
def analyze_base_classes(self, base_type_exprs): (source)

Analyze base class types.

Return None if some definition was incomplete. Otherwise, return a tuple with these items:

  • List of (analyzed type, original expression) tuples
  • Boolean indicating whether one of the bases had a semantic analysis error
Parameters
base​_type​_exprs:List[Expression]Undocumented
Returns
Optional[Tuple[List[Tuple[ProperType, Expression]], bool]]Undocumented
def analyze_class(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
def analyze_class_body_common(self, defn): (source)
Parts of class body analysis that are common to all kinds of class defs.
Parameters
defn:ClassDefUndocumented
def analyze_class_decorator(self, defn, decorator): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
decorator:ExpressionUndocumented
def analyze_class_keywords(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
def analyze_class_typevar_declaration(self, base): (source)

Analyze type variables declared using Generic[...] or Protocol[...].

Args:
base: Non-analyzed base class

Return None if the base class does not declare type variables. Otherwise, return the type variables.

Parameters
base:TypeUndocumented
Returns
Optional[Tuple[TypeVarLikeList, bool]]Undocumented
def analyze_comp_for(self, expr): (source)

Analyses the 'comp_for' part of comprehensions (part 1).

That is the part after 'for' in (x for x in l if p). This analyzes variables and conditions which are analyzed in a local scope.

Parameters
expr:Union[GeneratorExpr, DictionaryComprehension]Undocumented
def analyze_comp_for_2(self, expr): (source)

Analyses the 'comp_for' part of comprehensions (part 2).

That is the part after 'for' in (x for x in l if p). This analyzes the 'l' part which is analyzed in the surrounding scope.

Parameters
expr:Union[GeneratorExpr, DictionaryComprehension]Undocumented
def analyze_enum_assign(self, s): (source)
Check if s defines an Enum.
Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def analyze_func_def(self, defn): (source)

Undocumented

Parameters
defn:FuncDefUndocumented
def analyze_function_body(self, defn): (source)

Undocumented

Parameters
defn:FuncItemUndocumented
def analyze_identity_global_assignment(self, s): (source)

Special case 'X = X' in global scope.

This allows supporting some important use cases.

Return true if special casing was applied.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def analyze_lvalue(self, lval, nested=False, explicit_type=False, is_final=False, escape_comprehensions=False, has_explicit_value=False): (source)

Analyze an lvalue or assignment target.

Args:

lval: The target lvalue nested: If true, the lvalue is within a tuple or list lvalue expression explicit_type: Assignment has type annotation escape_comprehensions: If we are inside a comprehension, set the variable

in the enclosing scope instead. This implements https://www.python.org/dev/peps/pep-0572/#scope-of-the-target
Parameters
lval:LvalueUndocumented
nested:boolUndocumented
explicit​_type:boolUndocumented
is​_final:boolUndocumented
escape​_comprehensions:boolUndocumented
has​_explicit​_value:boolUndocumented
def analyze_lvalues(self, s): (source)

Undocumented

Parameters
s:AssignmentStmtUndocumented
def analyze_member_lvalue(self, lval, explicit_type, is_final): (source)

Analyze lvalue that is a member expression.

Arguments:
lval: The target lvalue explicit_type: Assignment has type annotation is_final: Is the target final
Parameters
lval:MemberExprUndocumented
explicit​_type:boolUndocumented
is​_final:boolUndocumented
def analyze_metaclass(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
def analyze_name_lvalue(self, lvalue, explicit_type, is_final, escape_comprehensions, has_explicit_value): (source)

Analyze an lvalue that targets a name expression.

Arguments are similar to "analyze_lvalue".

Parameters
lvalue:NameExprUndocumented
explicit​_type:boolUndocumented
is​_final:boolUndocumented
escape​_comprehensions:boolUndocumented
has​_explicit​_value:boolUndocumented
def analyze_namedtuple_assign(self, s): (source)
Check if s defines a namedtuple.
Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def analyze_namedtuple_classdef(self, defn): (source)
Check if this class can define a named tuple.
Parameters
defn:ClassDefUndocumented
Returns
boolUndocumented
def analyze_overload_sigs_and_impl(self, defn): (source)

Find overload signatures, the implementation, and items with missing @overload.

Assume that the first was already analyzed. As a side effect: analyzes remaining items and updates 'is_overload' flags.

Parameters
defn:OverloadedFuncDefUndocumented
Returns
Tuple[List[CallableType], Optional[OverloadPart], List[int]]Undocumented
def analyze_overloaded_func_def(self, defn): (source)

Undocumented

Parameters
defn:OverloadedFuncDefUndocumented
def analyze_property_with_multi_part_definition(self, defn): (source)

Analyze a property defined using multiple methods (e.g., using @x.setter).

Assume that the first method (@property) has already been analyzed.

Parameters
defn:OverloadedFuncDefUndocumented
def analyze_simple_literal_type(self, rvalue, is_final): (source)

Return builtins.int if rvalue is an int literal, etc.

If this is a 'Final' context, we return "Literal[...]" instead.

Parameters
rvalue:ExpressionUndocumented
is​_final:boolUndocumented
Returns
Optional[Type]Undocumented
def analyze_try_stmt(self, s, visitor): (source)

Undocumented

Parameters
s:TryStmtUndocumented
visitor:NodeVisitor[None]Undocumented
def analyze_tuple_or_list_lvalue(self, lval, explicit_type=False): (source)
Analyze an lvalue or assignment target that is a list or tuple.
Parameters
lval:TupleExprUndocumented
explicit​_type:boolUndocumented
def analyze_type_application(self, expr): (source)
Analyze special form -- type application (either direct or via type aliasing).
Parameters
expr:IndexExprUndocumented
def analyze_type_application_args(self, expr): (source)

Analyze type arguments (index) in a type application.

Return None if anything was incomplete.

Parameters
expr:IndexExprUndocumented
Returns
Optional[List[Type]]Undocumented
def analyze_type_expr(self, expr): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
def analyze_typeddict_assign(self, s): (source)
Check if s defines a typed dict.
Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def analyze_unbound_tvar(self, t): (source)

Undocumented

Parameters
t:TypeUndocumented
Returns
Optional[Tuple[str, TypeVarLikeExpr]]Undocumented
def analyze_value_types(self, items): (source)
Analyze types from values expressions in type variable definition.
Parameters
items:List[Expression]Undocumented
Returns
List[Type]Undocumented
def apply_class_plugin_hooks(self, defn): (source)
Apply a plugin hook that may infer a more precise definition for a class.
Parameters
defn:ClassDefUndocumented
def apply_dynamic_class_hook(self, s): (source)

Undocumented

Parameters
s:AssignmentStmtUndocumented
def attribute_already_defined(self, name, ctx, original_ctx=None): (source)

Undocumented

Parameters
name:strUndocumented
ctx:ContextUndocumented
original​_ctx:Optional[Union[SymbolTableNode, SymbolNode]]Undocumented
def basic_new_typeinfo(self, name, basetype_or_fallback, line): (source)

Undocumented

Parameters
name:strUndocumented
basetype​_or​_fallback:InstanceUndocumented
line:intUndocumented
Returns
TypeInfoUndocumented
def bind_name_expr(self, expr, sym): (source)
Bind name expression to a symbol table node.
Parameters
expr:NameExprUndocumented
sym:SymbolTableNodeUndocumented
def calculate_class_mro(self, defn, obj_type=None): (source)

Calculate method resolution order for a class.

obj_type may be omitted in the third pass when all classes are already analyzed. It exists just to fill in empty base class list during second pass in case of an import cycle.

Parameters
defn:ClassDefUndocumented
obj​_type:Optional[Callable[[], Instance]]Undocumented
def can_be_type_alias(self, rv, allow_none=False): (source)

Is this a valid r.h.s. for an alias definition?

Note: this function should be only called for expressions where self.should_wait_rhs() returns False.

Parameters
rv:ExpressionUndocumented
allow​_none:boolUndocumented
Returns
boolUndocumented
def cannot_resolve_name(self, name, kind, ctx): (source)

Undocumented

Parameters
name:strUndocumented
kind:strUndocumented
ctx:ContextUndocumented
def check_and_set_up_type_alias(self, s): (source)

Check if assignment creates a type alias and set it up as needed.

Return True if it is a type alias (even if the target is not ready), or False otherwise.

Note: the resulting types for subscripted (including generic) aliases are also stored in rvalue.analyzed.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def check_classvar(self, s): (source)
Check if assignment defines a class variable.
Parameters
s:AssignmentStmtUndocumented
def check_classvar_in_signature(self, typ): (source)

Undocumented

Parameters
typ:ProperTypeUndocumented
def check_decorated_function_is_method(self, decorator, context): (source)

Undocumented

Parameters
decorator:strUndocumented
context:ContextUndocumented
def check_final_implicit_def(self, s): (source)

Do basic checks for final declaration on self in __init__.

Additional re-definition checks are performed by analyze_lvalue.

Parameters
s:AssignmentStmtUndocumented
def check_fixed_args(self, expr, numargs, name): (source)

Verify that expr has specified number of positional args.

Return True if the arguments are valid.

Parameters
expr:CallExprUndocumented
numargs:intUndocumented
name:strUndocumented
Returns
boolUndocumented
def check_function_signature(self, fdef): (source)

Undocumented

Parameters
fdef:FuncItemUndocumented
def check_lvalue_validity(self, node, ctx): (source)

Undocumented

Parameters
node:Union[Expression, SymbolNode, None]Undocumented
ctx:ContextUndocumented
def check_no_global(self, name, ctx, is_overloaded_func=False): (source)

Undocumented

Parameters
name:strUndocumented
ctx:ContextUndocumented
is​_overloaded​_func:boolUndocumented
def check_typevarlike_name(self, call, name, context): (source)
Checks that the name of a TypeVar or ParamSpec matches its variable.
Parameters
call:CallExprUndocumented
name:strUndocumented
context:ContextUndocumented
Returns
boolUndocumented
def class_type(self, self_type): (source)
Generate type of first argument of class methods from type of self.
Parameters
self​_type:TypeUndocumented
Returns
TypeUndocumented
def clean_up_bases_and_infer_type_variables(self, defn, base_type_exprs, context): (source)

Remove extra base classes such as Generic and infer type vars.

For example, consider this class:

class Foo(Bar, Generic[T]): ...

Now we will remove Generic[T] from bases of Foo and infer that the type variable 'T' is a type argument of Foo.

Note that this is performed before semantic analysis.

Returns (remaining base expressions, inferred type variables, is protocol).

Parameters
defn:ClassDefUndocumented
base​_type​_exprs:List[Expression]Undocumented
context:ContextUndocumented
Returns
Tuple[List[Expression], List[TypeVarLikeType], bool]Undocumented
def configure_base_classes(self, defn, bases): (source)

Set up base classes.

This computes several attributes on the corresponding TypeInfo defn.info related to the base classes: defn.info.bases, defn.info.mro, and miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.)

Parameters
defn:ClassDefUndocumented
bases:List[Tuple[ProperType, Expression]]Undocumented
def configure_tuple_base_class(self, defn, base, base_expr): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
base:TupleTypeUndocumented
base​_expr:ExpressionUndocumented
Returns
InstanceUndocumented
def correct_relative_import(self, node): (source)

Undocumented

Parameters
node:Union[ImportFrom, ImportAll]Undocumented
Returns
strUndocumented
def create_alias(self, tree, target_name, alias, name): (source)

Undocumented

Parameters
tree:MypyFileUndocumented
target​_name:strUndocumented
alias:strUndocumented
name:strUndocumented
def create_getattr_var(self, getattr_defn, name, fullname): (source)

Create a dummy variable using module-level __getattr__ return type.

If not possible, return None.

Note that multiple Var nodes can be created for a single name. We can use the from_module_getattr and the fullname attributes to check if two dummy Var nodes refer to the same thing. Reusing Var nodes would require non-local mutable state, which we prefer to avoid.

Parameters
getattr​_defn:SymbolTableNodeUndocumented
name:strUndocumented
fullname:strUndocumented
Returns
Optional[Var]Undocumented
def current_symbol_kind(self): (source)

Undocumented

Returns
intUndocumented
def current_symbol_table(self, escape_comprehensions=False): (source)

Get currently active symbol table.

May be module, class, or local namespace.

Parameters
escape​_comprehensions:boolUndocumented
Returns
SymbolTableUndocumented
def defer(self, debug_context=None): (source)

Defer current analysis target to be analyzed again.

This must be called if something in the current target is incomplete or has a placeholder node. However, this must not be called during the final analysis iteration! Instead, an error should be generated. Often 'process_placeholder' is a good way to either defer or generate an error.

NOTE: Some methods, such as 'anal_type', 'mark_incomplete' and
'record_incomplete_ref', call this implicitly, or when needed. They are usually preferable to a direct defer() call.
Parameters
debug​_context:Optional[Context]Undocumented
@contextmanager
def enter(self, function): (source)
Enter a function, generator or comprehension scope.
Parameters
function:Union[FuncItem, GeneratorExpr, DictionaryComprehension]Undocumented
Returns
Iterator[None]Undocumented
def enter_class(self, info): (source)

Undocumented

Parameters
info:TypeInfoUndocumented
def enum_has_final_values(self, base): (source)

Undocumented

Parameters
base:InstanceUndocumented
Returns
boolUndocumented
def expr_to_analyzed_type(self, expr, report_invalid_types=True, allow_placeholder=False): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
report​_invalid​_types:boolUndocumented
allow​_placeholder:boolUndocumented
Returns
Optional[Type]Undocumented
def expr_to_unanalyzed_type(self, node): (source)

Undocumented

Parameters
node:ExpressionUndocumented
Returns
ProperTypeUndocumented
def fail(self, msg, ctx, serious=False, *, code=None, blocker=False): (source)
Emit an error message at given location.
Parameters
msg:strUndocumented
ctx:ContextUndocumented
serious:boolUndocumented
code:Optional[ErrorCode]Undocumented
blocker:boolUndocumented
def fail_blocker(self, msg, ctx): (source)

Undocumented

Parameters
msg:strUndocumented
ctx:ContextUndocumented
def fail_invalid_classvar(self, context): (source)

Undocumented

Parameters
context:ContextUndocumented
@contextmanager
def file_context(self, file_node, options, active_type=None): (source)

Configure analyzer for analyzing targets within a file/class.

Args:
file_node: target file options: options specific to the file active_type: must be the surrounding class to analyze method targets
Parameters
file​_node:MypyFileUndocumented
options:OptionsUndocumented
active​_type:Optional[TypeInfo]Undocumented
Returns
Iterator[None]Undocumented
def flatten_lvalues(self, lvalues): (source)

Undocumented

Parameters
lvalues:List[Expression]Undocumented
Returns
List[Expression]Undocumented
def found_incomplete_ref(self, tag): (source)
Have we encountered an incomplete reference since starting tracking?
Parameters
tag:TagUndocumented
Returns
boolUndocumented
def get_all_bases_tvars(self, base_type_exprs, removed): (source)
Return all type variable references in bases.
Parameters
base​_type​_exprs:List[Expression]Undocumented
removed:List[int]Undocumented
Returns
TypeVarLikeListUndocumented
def get_module_symbol(self, node, name): (source)

Look up a symbol from a module.

Return None if no matching symbol could be bound.

Parameters
node:MypyFileUndocumented
name:strUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def get_name_repr_of_expr(self, expr): (source)
Try finding a short simplified textual representation of a base class expression.
Parameters
expr:ExpressionUndocumented
Returns
Optional[str]Undocumented
def get_typevarlike_declaration(self, s, typevarlike_types): (source)
Returns the call expression if s is a declaration of typevarlike_type (TypeVar or ParamSpec), or None otherwise.
Parameters
s:AssignmentStmtUndocumented
typevarlike​_types:Tuple[str, ...]Undocumented
Returns
Optional[CallExpr]Undocumented
def handle_missing_overload_decorators(self, defn, non_overload_indexes, some_overload_decorators): (source)

Generate errors for overload items without @overload.

Side effect: remote non-overload items.

Parameters
defn:OverloadedFuncDefUndocumented
non​_overload​_indexes:List[int]Undocumented
some​_overload​_decorators:boolUndocumented
def handle_missing_overload_implementation(self, defn): (source)
Generate error about missing overload implementation (only if needed).
Parameters
defn:OverloadedFuncDefUndocumented
def implicit_symbol(self, sym, name, parts, source_type): (source)
Create symbol for a qualified name reference through Any type.
Parameters
sym:SymbolTableNodeUndocumented
name:strUndocumented
parts:List[str]Undocumented
source​_type:AnyTypeUndocumented
Returns
SymbolTableNodeUndocumented
def in_checked_function(self): (source)

Should we type-check the current function?

  • Yes if --check-untyped-defs is set.
  • Yes outside functions.
  • Yes in annotated functions.
  • No otherwise.
Returns
boolUndocumented
def is_active_symbol_in_class_body(self, node): (source)

Can a symbol defined in class body accessed at current statement?

Only allow access to class attributes textually after the definition, so that it's possible to fall back to the outer scope. Example:

class X: ...

class C:
X = X # Initializer refers to outer scope

Nested classes are an exception, since we want to support arbitrary forward references in type annotations.

Parameters
node:Optional[SymbolNode]Undocumented
Returns
boolUndocumented
def is_alias_for_final_name(self, name): (source)

Undocumented

Parameters
name:strUndocumented
Returns
boolUndocumented
def is_annotated_protocol_member(self, s): (source)

Check whether a protocol member is annotated.

There are some exceptions that can be left unannotated, like __slots__.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def is_base_class(self, t, s): (source)
Determine if t is a base class of s (but do not use mro).
Parameters
t:TypeInfoUndocumented
s:TypeInfoUndocumented
Returns
boolUndocumented
def is_class_scope(self): (source)

Undocumented

Returns
boolUndocumented
def is_classvar(self, typ): (source)

Undocumented

Parameters
typ:TypeUndocumented
Returns
boolUndocumented
def is_core_builtin_class(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
Returns
boolUndocumented
def is_defined_in_current_module(self, fullname): (source)

Undocumented

Parameters
fullname:Optional[str]Undocumented
Returns
boolUndocumented
def is_final_redefinition(self, kind, name): (source)

Undocumented

Parameters
kind:intUndocumented
name:strUndocumented
Returns
boolUndocumented
def is_final_type(self, typ): (source)

Undocumented

Parameters
typ:Optional[Type]Undocumented
Returns
boolUndocumented
def is_func_scope(self): (source)

Undocumented

Returns
boolUndocumented
def is_future_flag_set(self, flag): (source)
Is the specific __future__ feature imported
Parameters
flag:strUndocumented
Returns
boolUndocumented
def is_global_or_nonlocal(self, name): (source)

Undocumented

Parameters
name:strUndocumented
Returns
boolUndocumented
def is_incomplete_namespace(self, fullname): (source)

Is a module or class namespace potentially missing some definitions?

If a name is missing from an incomplete namespace, we'll need to defer the current analysis target.

Parameters
fullname:strUndocumented
Returns
boolUndocumented
def is_initial_mangled_global(self, name): (source)

Undocumented

Parameters
name:strUndocumented
Returns
boolUndocumented
def is_local_name(self, name): (source)
Does name look like reference to a definition in the current module?
Parameters
name:strUndocumented
Returns
boolUndocumented
def is_mangled_global(self, name): (source)

Undocumented

Parameters
name:strUndocumented
Returns
boolUndocumented
def is_missing_module(self, module): (source)

Undocumented

Parameters
module:strUndocumented
Returns
boolUndocumented
def is_module_scope(self): (source)

Undocumented

Returns
boolUndocumented
def is_nested_within_func_scope(self): (source)
Are we underneath a function scope, even if we are in a nested class also?
Returns
boolUndocumented
def is_none_alias(self, node): (source)

Is this a r.h.s. for a None alias?

We special case the assignments like Void = type(None), to allow using Void in type annotations.

Parameters
node:ExpressionUndocumented
Returns
boolUndocumented
def is_overloaded_item(self, node, statement): (source)
Check whether the function belongs to the overloaded variants
Parameters
node:SymbolNodeUndocumented
statement:StatementUndocumented
Returns
boolUndocumented
def is_self_member_ref(self, memberexpr): (source)
Does memberexpr to refer to an attribute of self?
Parameters
memberexpr:MemberExprUndocumented
Returns
boolUndocumented
def is_textually_before_statement(self, node): (source)

Check if a node is defined textually before the current statement

Note that decorated functions' line number are the same as the top decorator.

Parameters
node:SymbolNodeUndocumented
Returns
boolUndocumented
def is_type_ref(self, rv, bare=False): (source)

Does this expression refer to a type?

This includes:
  • Special forms, like Any or Union
  • Classes (except subscripted enums)
  • Other type aliases
  • PlaceholderNodes with becomes_typeinfo=True (these can be not ready class definitions, and not ready aliases).

If bare is True, this is not a base of an index expression, so some special forms are not valid (like a bare Union).

Note: This method should be only used in context of a type alias definition. This method can only return True for RefExprs, to check if C[int] is a valid target for type alias call this method on expr.base (i.e. on C in C[int]). See also can_be_type_alias().

Parameters
rv:ExpressionUndocumented
bare:boolUndocumented
Returns
boolUndocumented
def is_valid_del_target(self, s): (source)

Undocumented

Parameters
s:ExpressionUndocumented
Returns
boolUndocumented
def leave_class(self): (source)
Restore analyzer state.
def lookup(self, name, ctx, suppress_errors=False): (source)

Look up an unqualified (no dots) name in all active namespaces.

Note that the result may contain a PlaceholderNode. The caller may want to defer in that case.

Generate an error if the name is not defined unless suppress_errors is true or the current namespace is incomplete. In the latter case defer.

Parameters
name:strUndocumented
ctx:ContextUndocumented
suppress​_errors:boolUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def lookup_current_scope(self, name): (source)

Undocumented

Parameters
name:strUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def lookup_fully_qualified(self, fullname): (source)

Lookup a symbol by its fully qualified name.

Raise an error if not found.

Parameters
fullname:strUndocumented
Returns
SymbolTableNodeUndocumented
def lookup_fully_qualified_or_none(self, fullname): (source)

Lookup a fully qualified name that refers to a module-level definition.

Don't assume that the name is defined. This happens in the global namespace -- the local module namespace is ignored. This does not dereference indirect refs.

Note that this can't be used for names nested in class namespaces.

Parameters
fullname:strUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def lookup_qualified(self, name, ctx, suppress_errors=False): (source)

Lookup a qualified name in all activate namespaces.

Note that the result may contain a PlaceholderNode. The caller may want to defer in that case.

Generate an error if the name is not defined unless suppress_errors is true or the current namespace is incomplete. In the latter case defer.

Parameters
name:strUndocumented
ctx:ContextUndocumented
suppress​_errors:boolUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def lookup_type_node(self, expr): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
Returns
Optional[SymbolTableNode]Undocumented
def make_empty_type_info(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
Returns
TypeInfoUndocumented
def make_name_lvalue_point_to_existing_def(self, lval, explicit_type, is_final): (source)

Update an lvalue to point to existing definition in the same scope.

Arguments are similar to "analyze_lvalue".

Assume that an existing name exists.

Parameters
lval:NameExprUndocumented
explicit​_type:boolUndocumented
is​_final:boolUndocumented
def make_name_lvalue_var(self, lvalue, kind, inferred, has_explicit_value): (source)
Return a Var node for an lvalue that is a name expression.
Parameters
lvalue:NameExprUndocumented
kind:intUndocumented
inferred:boolUndocumented
has​_explicit​_value:boolUndocumented
Returns
VarUndocumented
def mark_incomplete(self, name, node, becomes_typeinfo=False, module_public=True, module_hidden=False): (source)

Mark a definition as incomplete (and defer current analysis target).

Also potentially mark the current namespace as incomplete.

Args:

name: The name that we weren't able to define (or '*' if the name is unknown) node: The node that refers to the name (definition or lvalue) becomes_typeinfo: Pass this to PlaceholderNode (used by special forms like

named tuples that will create TypeInfos).
Parameters
name:strUndocumented
node:NodeUndocumented
becomes​_typeinfo:boolUndocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
def name_already_defined(self, name, ctx, original_ctx=None): (source)

Undocumented

Parameters
name:strUndocumented
ctx:ContextUndocumented
original​_ctx:Optional[Union[SymbolTableNode, SymbolNode]]Undocumented
def name_not_defined(self, name, ctx, namespace=None): (source)

Undocumented

Parameters
name:strUndocumented
ctx:ContextUndocumented
namespace:Optional[str]Undocumented
def named_type(self, fullname, args=None): (source)
Construct an instance of a builtin type with given type arguments.
Parameters
fullname:strUndocumented
args:Optional[List[Type]]Undocumented
Returns
InstanceUndocumented
def named_type_or_none(self, fullname, args=None): (source)

Construct an instance of a type with given type arguments.

Return None if a type could not be constructed for the qualified type name. This is possible when the qualified name includes a module name and the module has not been imported.

Parameters
fullname:strUndocumented
args:Optional[List[Type]]Undocumented
Returns
Optional[Instance]Undocumented
def note(self, msg, ctx, code=None): (source)

Undocumented

Parameters
msg:strUndocumented
ctx:ContextUndocumented
code:Optional[ErrorCode]Undocumented
def object_type(self): (source)

Undocumented

Returns
InstanceUndocumented
def parse_bool(self, expr): (source)
Parse True/False literals.
Parameters
expr:ExpressionUndocumented
Returns
Optional[bool]Undocumented
def prepare_builtins_namespace(self, file_node): (source)

Add certain special-cased definitions to the builtins module.

Some definitions are too special or fundamental to be processed normally from the AST.

Parameters
file​_node:MypyFileUndocumented
def prepare_class_def(self, defn, info=None): (source)

Prepare for the analysis of a class definition.

Create an empty TypeInfo and store it in a symbol table, or if the 'info' argument is provided, store it instead (used for magic type definitions).

Parameters
defn:ClassDefUndocumented
info:Optional[TypeInfo]Undocumented
def prepare_file(self, file_node): (source)
Prepare a freshly parsed file for semantic analysis.
Parameters
file​_node:MypyFileUndocumented
def prepare_method_signature(self, func, info): (source)
Check basic signature validity and tweak annotation of self/cls argument.
Parameters
func:FuncDefUndocumented
info:TypeInfoUndocumented
def prepare_typing_namespace(self, file_node, aliases): (source)

Remove dummy alias definitions such as List = TypeAlias(object) from typing.

They will be replaced with real aliases when corresponding targets are ready.

Parameters
file​_node:MypyFileUndocumented
aliases:Dict[str, str]Undocumented
def process__all__(self, s): (source)
Export names if argument is a __all__ assignment.
Parameters
s:AssignmentStmtUndocumented
def process__deletable__(self, s): (source)

Undocumented

Parameters
s:AssignmentStmtUndocumented
def process__slots__(self, s): (source)

Processing __slots__ if defined in type.

See: https://docs.python.org/3/reference/datamodel.html#slots

Parameters
s:AssignmentStmtUndocumented
def process_final_in_overload(self, defn): (source)
Detect the @final status of an overloaded function (and perform checks).
Parameters
defn:OverloadedFuncDefUndocumented
def process_import_over_existing_name(self, imported_id, existing_symbol, module_symbol, import_node): (source)

Undocumented

Parameters
imported​_id:strUndocumented
existing​_symbol:SymbolTableNodeUndocumented
module​_symbol:SymbolTableNodeUndocumented
import​_node:ImportBaseUndocumented
Returns
boolUndocumented
def process_imported_symbol(self, node, module_id, id, imported_id, fullname, module_public, context): (source)

Undocumented

Parameters
node:SymbolTableNodeUndocumented
module​_id:strUndocumented
id:strUndocumented
imported​_id:strUndocumented
fullname:strUndocumented
module​_public:boolUndocumented
context:ImportBaseUndocumented
def process_module_assignment(self, lvals, rval, ctx): (source)

Propagate module references across assignments.

Recursively handles the simple form of iterable unpacking; doesn't handle advanced unpacking with *rest, dictionary unpacking, etc.

In an expression like x = y = z, z is the rval and lvals will be [x, y].

Parameters
lvals:List[Lvalue]Undocumented
rval:ExpressionUndocumented
ctx:AssignmentStmtUndocumented
def process_paramspec_declaration(self, s): (source)

Checks if s declares a ParamSpec; if yes, store it in symbol table.

Return True if this looks like a ParamSpec (maybe with errors), otherwise return False.

In the future, ParamSpec may accept bounds and variance arguments, in which case more aggressive sharing of code with process_typevar_declaration should be pursued.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def process_placeholder(self, name, kind, ctx): (source)

Process a reference targeting placeholder node.

If this is not a final iteration, defer current node, otherwise report an error.

The 'kind' argument indicates if this a name or attribute expression (used for better error message).

Parameters
name:strUndocumented
kind:strUndocumented
ctx:ContextUndocumented
def process_static_or_class_method_in_overload(self, defn): (source)

Undocumented

Parameters
defn:OverloadedFuncDefUndocumented
def process_type_annotation(self, s): (source)
Analyze type annotation or infer simple literal type.
Parameters
s:AssignmentStmtUndocumented
def process_typevar_declaration(self, s): (source)

Check if s declares a TypeVar; it yes, store it in symbol table.

Return True if this looks like a type variable declaration (but maybe with errors), otherwise return False.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def process_typevar_parameters(self, args, names, kinds, num_values, context): (source)

Undocumented

Parameters
args:List[Expression]Undocumented
names:List[Optional[str]]Undocumented
kinds:List[ArgKind]Undocumented
num​_values:intUndocumented
context:ContextUndocumented
Returns
Optional[Tuple[int, Type]]Undocumented
def qualified_name(self, name): (source)
Make qualified name using current module and enclosing class (if any).
Parameters
name:strUndocumented
Returns
strUndocumented
def record_incomplete_ref(self): (source)
Record the encounter of an incomplete reference and defer current analysis target.
def record_special_form_lvalue(self, s): (source)

Record minimal necessary information about l.h.s. of a special form.

This exists mostly for compatibility with the old semantic analyzer.

Parameters
s:AssignmentStmtUndocumented
def refresh_partial(self, node, patches, final_iteration, file_node, options, active_type=None): (source)
Refresh a stale target in fine-grained incremental mode.
Parameters
node:Union[MypyFile, FuncDef, OverloadedFuncDef]Undocumented
patches:List[Tuple[int, Callable[[], None]]]Undocumented
final​_iteration:boolUndocumented
file​_node:MypyFileUndocumented
options:OptionsUndocumented
active​_type:Optional[TypeInfo]Undocumented
def refresh_top_level(self, file_node): (source)
Reanalyze a stale module top-level in fine-grained incremental mode.
Parameters
file​_node:MypyFileUndocumented
def report_hang(self): (source)

Undocumented

def report_missing_module_attribute(self, import_id, source_id, imported_id, module_public, module_hidden, context): (source)

Undocumented

Parameters
import​_id:strUndocumented
source​_id:strUndocumented
imported​_id:strUndocumented
module​_public:boolUndocumented
module​_hidden:boolUndocumented
context:NodeUndocumented
def schedule_patch(self, priority, patch): (source)

Undocumented

Parameters
priority:intUndocumented
patch:Callable[[], None]Undocumented
def set_dummy_mro(self, info): (source)

Undocumented

Parameters
info:TypeInfoUndocumented
def set_future_import_flags(self, module_name): (source)

Undocumented

Parameters
module​_name:strUndocumented
def set_original_def(self, previous, new): (source)

If 'new' conditionally redefine 'previous', set 'previous' as original

We reject straight redefinitions of functions, as they are usually a programming error. For example:

def f(): ... def f(): ... # Error: 'f' redefined
Parameters
previous:Optional[Node]Undocumented
new:Union[FuncDef, Decorator]Undocumented
Returns
boolUndocumented
def should_wait_rhs(self, rv): (source)

Can we already classify this r.h.s. of an assignment or should we wait?

This returns True if we don't have enough information to decide whether an assignment is just a normal variable definition or a special form. Always return False if this is a final iteration. This will typically cause the lvalue to be classified as a variable plus emit an error.

Parameters
rv:ExpressionUndocumented
Returns
boolUndocumented
def store_declared_types(self, lvalue, typ): (source)

Undocumented

Parameters
lvalue:LvalueUndocumented
typ:TypeUndocumented
def store_final_status(self, s): (source)
If this is a locally valid final declaration, set the corresponding flag on Var.
Parameters
s:AssignmentStmtUndocumented
def str_type(self): (source)

Undocumented

Returns
InstanceUndocumented
def track_incomplete_refs(self): (source)
Return tag that can be used for tracking references to incomplete names.
Returns
TagUndocumented
def translate_dict_call(self, call): (source)

Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}.

For other variants of dict(...), return None.

Parameters
call:CallExprUndocumented
Returns
Optional[DictExpr]Undocumented
@contextmanager
def tvar_scope_frame(self, frame): (source)

Undocumented

Parameters
frame:TypeVarLikeScopeUndocumented
Returns
Iterator[None]Undocumented
def type_analyzer(self, *, tvar_scope=None, allow_tuple_literal=False, allow_unbound_tvars=False, allow_placeholder=False, allow_required=False, report_invalid_types=True): (source)

Undocumented

Parameters
tvar​_scope:Optional[TypeVarLikeScope]Undocumented
allow​_tuple​_literal:boolUndocumented
allow​_unbound​_tvars:boolUndocumented
allow​_placeholder:boolUndocumented
allow​_required:boolUndocumented
report​_invalid​_types:boolUndocumented
Returns
TypeAnalyserUndocumented
def unbox_literal(self, e): (source)

Undocumented

Parameters
e:ExpressionUndocumented
Returns
Optional[Union[int, float, bool, str]]Undocumented
def unwrap_final(self, s): (source)

Strip Final[...] if present in an assignment.

This is done to invoke type inference during type checking phase for this assignment. Also, Final[...] doesn't affect type in any way -- it is rather an access qualifier for given Var.

Also perform various consistency checks.

Returns True if Final[...] was present.

Parameters
s:AssignmentStmtUndocumented
Returns
boolUndocumented
def update_function_type_variables(self, fun_type, defn): (source)

Make any type variables in the signature of defn explicit.

Update the signature of defn to contain type variable definitions if defn is generic.

Parameters
fun​_type:CallableTypeUndocumented
defn:FuncItemUndocumented
def update_metaclass(self, defn): (source)

Lookup for special metaclass declarations, and update defn fields accordingly.

  • __metaclass__ attribute in Python 2
  • six.with_metaclass(M, B1, B2, ...)
  • @six.add_metaclass(M)
  • future.utils.with_metaclass(M, B1, B2, ...)
  • past.utils.with_metaclass(M, B1, B2, ...)
Parameters
defn:ClassDefUndocumented
def verify_base_classes(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
Returns
boolUndocumented
def visit__promote_expr(self, expr): (source)

Undocumented

Parameters
expr:PromoteExprUndocumented
def visit_assert_stmt(self, s): (source)

Undocumented

Parameters
s:AssertStmtUndocumented
def visit_assignment_expr(self, s): (source)

Undocumented

Parameters
s:AssignmentExprUndocumented
def visit_assignment_stmt(self, s): (source)

Undocumented

Parameters
s:AssignmentStmtUndocumented
def visit_await_expr(self, expr): (source)

Undocumented

Parameters
expr:AwaitExprUndocumented
def visit_backquote_expr(self, expr): (source)

Undocumented

Parameters
expr:BackquoteExprUndocumented
def visit_block(self, b): (source)

Undocumented

Parameters
b:BlockUndocumented
def visit_block_maybe(self, b): (source)

Undocumented

Parameters
b:Optional[Block]Undocumented
def visit_break_stmt(self, s): (source)

Undocumented

Parameters
s:BreakStmtUndocumented
def visit_call_expr(self, expr): (source)

Analyze a call expression.

Some call expressions are recognized as special forms, including cast(...).

Parameters
expr:CallExprUndocumented
def visit_cast_expr(self, expr): (source)

Undocumented

Parameters
expr:CastExprUndocumented
def visit_class_def(self, defn): (source)

Undocumented

Parameters
defn:ClassDefUndocumented
def visit_comparison_expr(self, expr): (source)

Undocumented

Parameters
expr:ComparisonExprUndocumented
def visit_conditional_expr(self, expr): (source)

Undocumented

Parameters
expr:ConditionalExprUndocumented
def visit_continue_stmt(self, s): (source)

Undocumented

Parameters
s:ContinueStmtUndocumented
def visit_decorator(self, dec): (source)

Undocumented

Parameters
dec:DecoratorUndocumented
def visit_del_stmt(self, s): (source)

Undocumented

Parameters
s:DelStmtUndocumented
def visit_dict_expr(self, expr): (source)

Undocumented

Parameters
expr:DictExprUndocumented
def visit_dictionary_comprehension(self, expr): (source)

Undocumented

Parameters
expr:DictionaryComprehensionUndocumented
def visit_exec_stmt(self, s): (source)

Undocumented

Parameters
s:ExecStmtUndocumented
def visit_expression_stmt(self, s): (source)

Undocumented

Parameters
s:ExpressionStmtUndocumented
def visit_for_stmt(self, s): (source)

Undocumented

Parameters
s:ForStmtUndocumented
def visit_func_def(self, defn): (source)

Undocumented

Parameters
defn:FuncDefUndocumented
def visit_generator_expr(self, expr): (source)

Undocumented

Parameters
expr:GeneratorExprUndocumented
def visit_global_decl(self, g): (source)

Undocumented

Parameters
g:GlobalDeclUndocumented
def visit_if_stmt(self, s): (source)

Undocumented

Parameters
s:IfStmtUndocumented
def visit_import(self, i): (source)

Undocumented

Parameters
i:ImportUndocumented
def visit_import_all(self, i): (source)

Undocumented

Parameters
i:ImportAllUndocumented
def visit_import_from(self, imp): (source)

Undocumented

Parameters
imp:ImportFromUndocumented
def visit_index_expr(self, expr): (source)

Undocumented

Parameters
expr:IndexExprUndocumented
def visit_lambda_expr(self, expr): (source)

Undocumented

Parameters
expr:LambdaExprUndocumented
def visit_list_comprehension(self, expr): (source)

Undocumented

Parameters
expr:ListComprehensionUndocumented
def visit_list_expr(self, expr): (source)

Undocumented

Parameters
expr:ListExprUndocumented
def visit_member_expr(self, expr): (source)

Undocumented

Parameters
expr:MemberExprUndocumented
def visit_name_expr(self, expr): (source)

Undocumented

Parameters
expr:NameExprUndocumented
def visit_nonlocal_decl(self, d): (source)

Undocumented

Parameters
d:NonlocalDeclUndocumented
def visit_op_expr(self, expr): (source)

Undocumented

Parameters
expr:OpExprUndocumented
def visit_operator_assignment_stmt(self, s): (source)

Undocumented

Parameters
s:OperatorAssignmentStmtUndocumented
def visit_overloaded_func_def(self, defn): (source)

Undocumented

Parameters
defn:OverloadedFuncDefUndocumented
def visit_print_stmt(self, s): (source)

Undocumented

Parameters
s:PrintStmtUndocumented
def visit_raise_stmt(self, s): (source)

Undocumented

Parameters
s:RaiseStmtUndocumented
def visit_return_stmt(self, s): (source)

Undocumented

Parameters
s:ReturnStmtUndocumented
def visit_reveal_expr(self, expr): (source)

Undocumented

Parameters
expr:RevealExprUndocumented
def visit_set_comprehension(self, expr): (source)

Undocumented

Parameters
expr:SetComprehensionUndocumented
def visit_set_expr(self, expr): (source)

Undocumented

Parameters
expr:SetExprUndocumented
def visit_slice_expr(self, expr): (source)

Undocumented

Parameters
expr:SliceExprUndocumented
def visit_star_expr(self, expr): (source)

Undocumented

Parameters
expr:StarExprUndocumented
def visit_super_expr(self, expr): (source)

Undocumented

Parameters
expr:SuperExprUndocumented
def visit_try_stmt(self, s): (source)

Undocumented

Parameters
s:TryStmtUndocumented
def visit_tuple_expr(self, expr): (source)

Undocumented

Parameters
expr:TupleExprUndocumented
def visit_type_application(self, expr): (source)

Undocumented

Parameters
expr:TypeApplicationUndocumented
def visit_unary_expr(self, expr): (source)

Undocumented

Parameters
expr:UnaryExprUndocumented
def visit_while_stmt(self, s): (source)

Undocumented

Parameters
s:WhileStmtUndocumented
def visit_with_stmt(self, s): (source)

Undocumented

Parameters
s:WithStmtUndocumented
def visit_yield_expr(self, expr): (source)

Undocumented

Parameters
expr:YieldExprUndocumented
def visit_yield_from_expr(self, e): (source)

Undocumented

Parameters
e:YieldFromExprUndocumented
__deletable__: list[str] = (source)

Undocumented

global_decls: List[Set[str]] = (source)

Undocumented

nonlocal_decls: List[Set[str]] = (source)

Undocumented

progress: bool = (source)

Undocumented

wrapped_coro_return_types: Dict[FuncDef, Type] = (source)

Undocumented

all_exports: list = (source)

Undocumented

block_depth: list[int] = (source)

Undocumented

cur_mod_node = (source)

Undocumented

deferral_debug_context: List[Tuple[str, int]] = (source)

Undocumented

deferred: bool = (source)

Undocumented

enum_call_analyzer = (source)

Undocumented

errors = (source)

Undocumented

export_map: Dict[str, List[str]] = (source)

Undocumented

function_stack: list = (source)

Undocumented

future_import_flags: Set[str] = (source)

Undocumented

globals = (source)

Undocumented

imports = (source)

Undocumented

incomplete: bool = (source)

Undocumented

incomplete_namespaces = (source)

Undocumented

incomplete_type_stack: List[bool] = (source)

Undocumented

is_comprehension_stack: list[bool] = (source)

Undocumented

locals: list = (source)

Undocumented

loop_depth: int = (source)

Undocumented

missing_modules = (source)

Undocumented

missing_names = (source)

Undocumented

named_tuple_analyzer = (source)

Undocumented

newtype_analyzer = (source)

Undocumented

num_incomplete_refs: int = (source)

Undocumented

patches = (source)

Undocumented

plugin = (source)

Undocumented

recurse_into_functions: bool = (source)

Undocumented

Undocumented

scope = (source)

Undocumented

statement = (source)

Undocumented

tvar_scope = (source)

Undocumented

type = (source)

Undocumented

type_stack: list = (source)

Undocumented

typed_dict_analyzer = (source)

Undocumented

@property
final_iteration: bool = (source)
Is this the final iteration of semantic analysis?
@property
is_stub_file: bool = (source)
@property
is_typeshed_stub_file: bool = (source)
_final_iteration = (source)

Undocumented

_is_stub_file = (source)

Undocumented

_is_typeshed_stub_file = (source)

Undocumented