class documentation

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_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 allow_unbound_tvars_set Undocumented
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_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_typeddict_classdef Undocumented
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 builtin_type Legacy function -- use named_type() instead.
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 can_possibly_be_type_form Like can_be_type_alias(), but simpler and doesn't require fully analyzed rvalue.
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_paramspec_definition Undocumented
Method check_typevarlike_name Checks that the name of a TypeVar or ParamSpec matches its variable.
Method check_valid_comprehension Check that assignment expression is not nested within comprehension at class scope.
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 disable_invalid_recursive_aliases Prohibit and fix recursive type aliases that are invalid/unsupported.
Method enter Enter a function, generator or comprehension scope.
Method enter_class Undocumented
Method expr_to_analyzed_type Undocumented
Method expr_to_unanalyzed_type Undocumented
Method extract_typevarlike_name Undocumented
Method fail Emit an error message at given location.
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_and_bind_all_tvars Return all type variable references in item type expressions.
Method get_declared_metaclass Get declared metaclass from metaclass expression.
Method get_fullname_for_hook Undocumented
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 incomplete_feature_enabled Undocumented
Method infer_metaclass_and_bases_from_compat_helpers Lookup for special metaclass declarations, and update defn fields accordingly.
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_expected_self_type Does this (analyzed or not) type represent the expected Self type for a method?
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_pep_613 Undocumented
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 parse_dataclass_transform_field_specifiers Undocumented
Method parse_dataclass_transform_spec Build a DataclassTransformSpec from the arguments passed to the given call to typing.dataclass_transform.
Method parse_str_literal Attempt to find the string literal value of the given expression. Returns `None` if no literal value can be found.
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_overload_impl Set flags for an overload implementation.
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 process_typevartuple_declaration Checks if s declares a TypeVarTuple; if yes, store it in symbol table.
Method qualified_name Make qualified name using current module and enclosing class (if any).
Method recalculate_metaclass Undocumented
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 remove_unpack_kwargs Undocumented
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 setup_alias_type_vars Undocumented
Method setup_self_type Setup a (shared) Self type variable for current class.
Method setup_type_vars Undocumented
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 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 verify_base_classes Undocumented
Method visit__promote_expr Undocumented
Method visit_as_pattern Undocumented
Method visit_assert_stmt Undocumented
Method visit_assert_type_expr Undocumented
Method visit_assignment_expr Undocumented
Method visit_assignment_stmt Undocumented
Method visit_await_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_class_pattern 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_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_mapping_pattern Undocumented
Method visit_match_stmt 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_or_pattern Undocumented
Method visit_overloaded_func_def Undocumented
Method visit_raise_stmt Undocumented
Method visit_return_stmt Undocumented
Method visit_reveal_expr Undocumented
Method visit_sequence_pattern Undocumented
Method visit_set_comprehension Undocumented
Method visit_set_expr Undocumented
Method visit_slice_expr Undocumented
Method visit_star_expr Undocumented
Method visit_starred_pattern 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_value_pattern 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 wrapped_coro_return_types Undocumented
Instance Variable all_exports Undocumented
Instance Variable allow_unbound_tvars Undocumented
Instance Variable basic_type_applications 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 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 progress 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_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
Property type Undocumented
Method _get_node_for_class_scoped_import Undocumented
Instance Variable _final_iteration Undocumented
Instance Variable _is_stub_file Undocumented
Instance Variable _is_typeshed_stub_file Undocumented
Instance Variable _type Undocumented

Inherited from NodeVisitor:

Method visit_bytes_expr Undocumented
Method visit_complex_expr Undocumented
Method visit_ellipsis Undocumented
Method visit_enum_call_expr Undocumented
Method visit_float_expr Undocumented
Method visit_int_expr Undocumented
Method visit_mypy_file Undocumented
Method visit_namedtuple_expr Undocumented
Method visit_newtype_expr Undocumented
Method visit_paramspec_expr Undocumented
Method visit_pass_stmt Undocumented
Method visit_placeholder_node Undocumented
Method visit_singleton_pattern Undocumented
Method visit_str_expr Undocumented
Method visit_temp_node Undocumented
Method visit_type_alias Undocumented
Method visit_type_alias_expr Undocumented
Method visit_type_var_expr Undocumented
Method visit_type_var_tuple_expr Undocumented
Method visit_typeddict_expr Undocumented
Method visit_var Undocumented
def __init__(self, modules: dict[str, MypyFile], missing_modules: set[str], incomplete_namespaces: set[str], errors: Errors, plugin: 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

def add_builtin_aliases(self, tree: MypyFile): (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]`.

def add_exports(self, exp_or_exps: Iterable[Expression]|Expression): (source)

Undocumented

def add_function_to_symbol_table(self, func: FuncDef|OverloadedFuncDef): (source)

Undocumented

def add_implicit_module_attrs(self, file_node: MypyFile): (source)

Manually add implicit definitions of module '__name__' etc.

def add_imported_symbol(self, name: str, node: SymbolTableNode, context: ImportBase, module_public: bool, module_hidden: bool): (source)

Add an alias to an existing symbol through import.

def add_local(self, node: (Var|FuncDef)|OverloadedFuncDef, context: Context): (source)

Add local variable or function.

def add_plugin_dependency(self, trigger: str, target: str|None = None): (source)

Add dependency from trigger to a target. If the target is not given explicitly, use the current target.

def add_redefinition(self, names: SymbolTable, name: str, symbol: SymbolTableNode): (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).

def add_symbol(self, name: str, node: SymbolNode, context: Context, module_public: bool = True, module_hidden: bool = False, can_defer: bool = True, escape_comprehensions: bool = False) -> bool: (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.

def add_symbol_skip_local(self, name: str, node: SymbolNode): (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.

def add_symbol_table_node(self, name: str, symbol: SymbolTableNode, context: Context|None = None, can_defer: bool = True, escape_comprehensions: bool = False) -> bool: (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)

def add_type_alias_deps(self, aliases_used: Collection[str], target: str|None = 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.

def add_typing_extension_aliases(self, tree: MypyFile): (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.

def add_unknown_imported_symbol(self, name: str, context: Context, target_name: str|None, module_public: bool, module_hidden: bool): (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.

def adjust_public_exports(self): (source)

Adjust the module visibility of globals due to __all__.

@contextmanager
def allow_unbound_tvars_set(self) -> Iterator[None]: (source)

Undocumented

def already_defined(self, name: str, ctx: Context, original_ctx: (SymbolTableNode|SymbolNode)|None, noun: str): (source)

Undocumented

def anal_type(self, typ: Type, *, tvar_scope: TypeVarLikeScope|None = None, allow_tuple_literal: bool = False, allow_unbound_tvars: bool = False, allow_placeholder: bool = False, allow_required: bool = False, allow_param_spec_literals: bool = False, report_invalid_types: bool = True, prohibit_self_type: str|None = None, allow_type_any: bool = False, third_pass: bool = False) -> Type|None: (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.

def analyze_alias(self, name: str, rvalue: Expression, allow_placeholder: bool = False) -> tuple[Type|None, list[TypeVarLikeType], set[str], list[str]]: (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. A schematic example for the dependencies: A = int B = str analyze_alias(Dict[A, B])[2] == {'__main__.A', '__main__.B'}

def analyze_arg_initializers(self, defn: FuncItem): (source)

Undocumented

def analyze_base_classes(self, base_type_exprs: list[Expression]) -> tuple[list[tuple[ProperType, Expression]], bool]|None: (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

def analyze_class(self, defn: ClassDef): (source)

Undocumented

def analyze_class_body_common(self, defn: ClassDef): (source)

Parts of class body analysis that are common to all kinds of class defs.

def analyze_class_decorator(self, defn: ClassDef, decorator: Expression): (source)

Undocumented

def analyze_class_keywords(self, defn: ClassDef): (source)

Undocumented

def analyze_class_typevar_declaration(self, base: Type) -> tuple[TypeVarLikeList, bool]|None: (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.

def analyze_comp_for(self, expr: GeneratorExpr|DictionaryComprehension): (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.

def analyze_comp_for_2(self, expr: GeneratorExpr|DictionaryComprehension): (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.

def analyze_enum_assign(self, s: AssignmentStmt) -> bool: (source)

Check if s defines an Enum.

def analyze_func_def(self, defn: FuncDef): (source)

Undocumented

def analyze_function_body(self, defn: FuncItem): (source)

Undocumented

def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool: (source)

Special case 'X = X' in global scope. This allows supporting some important use cases. Return true if special casing was applied.

def analyze_lvalue(self, lval: Lvalue, nested: bool = False, explicit_type: bool = False, is_final: bool = False, escape_comprehensions: bool = False, has_explicit_value: bool = 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

def analyze_lvalues(self, s: AssignmentStmt): (source)

Undocumented

def analyze_member_lvalue(self, lval: MemberExpr, explicit_type: bool, is_final: bool): (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

def analyze_name_lvalue(self, lvalue: NameExpr, explicit_type: bool, is_final: bool, escape_comprehensions: bool, has_explicit_value: bool): (source)

Analyze an lvalue that targets a name expression. Arguments are similar to "analyze_lvalue".

def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool: (source)

Check if s defines a namedtuple.

def analyze_namedtuple_classdef(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]) -> bool: (source)

Check if this class can define a named tuple.

def analyze_overload_sigs_and_impl(self, defn: OverloadedFuncDef) -> tuple[list[CallableType], OverloadPart|None, list[int]]: (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.

def analyze_overloaded_func_def(self, defn: OverloadedFuncDef): (source)

Undocumented

def analyze_property_with_multi_part_definition(self, defn: OverloadedFuncDef): (source)

Analyze a property defined using multiple methods (e.g., using @x.setter). Assume that the first method (@property) has already been analyzed.

def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type|None: (source)

Return builtins.int if rvalue is an int literal, etc. If this is a 'Final' context, we return "Literal[...]" instead.

def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None]): (source)

Undocumented

def analyze_tuple_or_list_lvalue(self, lval: TupleExpr, explicit_type: bool = False): (source)

Analyze an lvalue or assignment target that is a list or tuple.

def analyze_type_application(self, expr: IndexExpr): (source)

Analyze special form -- type application (either direct or via type aliasing).

def analyze_type_application_args(self, expr: IndexExpr) -> list[Type]|None: (source)

Analyze type arguments (index) in a type application. Return None if anything was incomplete.

def analyze_type_expr(self, expr: Expression): (source)

Undocumented

def analyze_typeddict_assign(self, s: AssignmentStmt) -> bool: (source)

Check if s defines a typed dict.

def analyze_typeddict_classdef(self, defn: ClassDef) -> bool: (source)

Undocumented

def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr]|None: (source)

Undocumented

def analyze_value_types(self, items: list[Expression]) -> list[Type]: (source)

Analyze types from values expressions in type variable definition.

def apply_class_plugin_hooks(self, defn: ClassDef): (source)

Apply a plugin hook that may infer a more precise definition for a class.

def apply_dynamic_class_hook(self, s: AssignmentStmt): (source)

Undocumented

def attribute_already_defined(self, name: str, ctx: Context, original_ctx: (SymbolTableNode|SymbolNode)|None = None): (source)

Undocumented

def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: (source)
def bind_name_expr(self, expr: NameExpr, sym: SymbolTableNode): (source)

Bind name expression to a symbol table node.

def builtin_type(self, fully_qualified_name: str) -> Instance: (source)

Legacy function -- use named_type() instead.

def calculate_class_mro(self, defn: ClassDef, obj_type: Callable[[], Instance]|None = None): (source)

Calculate method resolution order for a class. `obj_type` exists just to fill in empty base class list in case of an error.

def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool: (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.

def can_possibly_be_type_form(self, s: AssignmentStmt) -> bool: (source)

Like can_be_type_alias(), but simpler and doesn't require fully analyzed rvalue. Instead, use lvalues/annotations structure to figure out whether this can potentially be a type alias definition, NamedTuple, or TypedDict. Another difference from above function is that we are only interested IndexExpr, CallExpr and OpExpr rvalues, since only those can be potentially recursive (things like `A = A` are never valid).

def cannot_resolve_name(self, name: str|None, kind: str, ctx: Context): (source)

Undocumented

def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: (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.

def check_classvar(self, s: AssignmentStmt): (source)

Check if assignment defines a class variable.

def check_classvar_in_signature(self, typ: ProperType): (source)

Undocumented

def check_decorated_function_is_method(self, decorator: str, context: Context): (source)

Undocumented

def check_final_implicit_def(self, s: AssignmentStmt): (source)

Do basic checks for final declaration on self in __init__. Additional re-definition checks are performed by `analyze_lvalue`.

def check_fixed_args(self, expr: CallExpr, numargs: int, name: str) -> bool: (source)

Verify that expr has specified number of positional args. Return True if the arguments are valid.

def check_function_signature(self, fdef: FuncItem): (source)

Undocumented

def check_lvalue_validity(self, node: (Expression|SymbolNode)|None, ctx: Context): (source)

Undocumented

def check_paramspec_definition(self, defn: FuncDef): (source)

Undocumented

def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) -> bool: (source)

Checks that the name of a TypeVar or ParamSpec matches its variable.

def check_valid_comprehension(self, s: AssignmentExpr) -> bool: (source)

Check that assignment expression is not nested within comprehension at class scope. class C: [(j := i) for i in [1, 2, 3]] is a syntax error that is not enforced by Python parser, but at later steps.

def class_type(self, self_type: Type) -> Type: (source)

Generate type of first argument of class methods from type of self.

def clean_up_bases_and_infer_type_variables(self, defn: ClassDef, base_type_exprs: list[Expression], context: Context) -> tuple[list[Expression], list[TypeVarLikeType], bool]: (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).

def configure_base_classes(self, defn: ClassDef, bases: list[tuple[ProperType, Expression]]): (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.)

def configure_tuple_base_class(self, defn: ClassDef, base: TupleType) -> Instance: (source)

Undocumented

def correct_relative_import(self, node: ImportFrom|ImportAll) -> str: (source)

Undocumented

def create_alias(self, tree: MypyFile, target_name: str, alias: str, name: str): (source)

Undocumented

def create_getattr_var(self, getattr_defn: SymbolTableNode, name: str, fullname: str) -> Var|None: (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.

def current_symbol_kind(self) -> int: (source)

Undocumented

def current_symbol_table(self, escape_comprehensions: bool = False) -> SymbolTable: (source)

Get currently active symbol table. May be module, class, or local namespace.

def defer(self, debug_context: Context|None = None, force_progress: bool = False): (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.

def disable_invalid_recursive_aliases(self, s: AssignmentStmt, current_node: TypeAlias): (source)

Prohibit and fix recursive type aliases that are invalid/unsupported.

Enter a function, generator or comprehension scope.

def enter_class(self, info: TypeInfo): (source)

Undocumented

def expr_to_analyzed_type(self, expr: Expression, report_invalid_types: bool = True, allow_placeholder: bool = False, allow_type_any: bool = False) -> Type|None: (source)

Undocumented

def expr_to_unanalyzed_type(self, node: Expression) -> ProperType: (source)

Undocumented

def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str|None: (source)

Undocumented

def fail(self, msg: str, ctx: Context, serious: bool = False, *, code: ErrorCode|None = None, blocker: bool = False): (source)

Emit an error message at given location.

def fail_invalid_classvar(self, context: Context): (source)

Undocumented

@contextmanager
def file_context(self, file_node: MypyFile, options: Options, active_type: TypeInfo|None = None) -> Iterator[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

def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]: (source)

Undocumented

def found_incomplete_ref(self, tag: Tag) -> bool: (source)

Have we encountered an incomplete reference since starting tracking?

def get_all_bases_tvars(self, base_type_exprs: list[Expression], removed: list[int]) -> TypeVarLikeList: (source)

Return all type variable references in bases.

def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: (source)

Return all type variable references in item type expressions. This is a helper for generic TypedDicts and NamedTuples. Essentially it is a simplified version of the logic we use for ClassDef bases. We duplicate some amount of code, because it is hard to refactor common pieces.

def get_declared_metaclass(self, name: str, metaclass_expr: Expression|None) -> tuple[Instance|None, bool, bool]: (source)

Get declared metaclass from metaclass expression. Returns a tuple of three values: * A metaclass instance or None * A boolean indicating whether we should defer * A boolean indicating whether we should set metaclass Any fallback (either for Any metaclass or invalid/dynamic metaclass). The two boolean flags can only be True if instance is None.

def get_fullname_for_hook(self, expr: Expression) -> str|None: (source)

Undocumented

def get_module_symbol(self, node: MypyFile, name: str) -> SymbolTableNode|None: (source)

Look up a symbol from a module. Return None if no matching symbol could be bound.

def get_name_repr_of_expr(self, expr: Expression) -> str|None: (source)

Try finding a short simplified textual representation of a base class expression.

def get_typevarlike_declaration(self, s: AssignmentStmt, typevarlike_types: tuple[str, ...]) -> CallExpr|None: (source)

Returns the call expression if `s` is a declaration of `typevarlike_type` (TypeVar or ParamSpec), or None otherwise.

def handle_missing_overload_decorators(self, defn: OverloadedFuncDef, non_overload_indexes: list[int], some_overload_decorators: bool): (source)

Generate errors for overload items without @overload. Side effect: remote non-overload items.

def handle_missing_overload_implementation(self, defn: OverloadedFuncDef): (source)

Generate error about missing overload implementation (only if needed).

def implicit_symbol(self, sym: SymbolTableNode, name: str, parts: list[str], source_type: AnyType) -> SymbolTableNode: (source)

Create symbol for a qualified name reference through Any type.

def in_checked_function(self) -> bool: (source)

Should we type-check the current function? - Yes if --check-untyped-defs is set. - Yes outside functions. - Yes in annotated functions. - No otherwise.

def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: (source)
def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef): (source)

Lookup for special metaclass declarations, and update defn fields accordingly. * six.with_metaclass(M, B1, B2, ...) * @six.add_metaclass(M) * future.utils.with_metaclass(M, B1, B2, ...) * past.utils.with_metaclass(M, B1, B2, ...)

def is_active_symbol_in_class_body(self, node: SymbolNode|None) -> bool: (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. Also, we allow forward references to type aliases to support recursive types.

def is_alias_for_final_name(self, name: str) -> bool: (source)

Undocumented

def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool: (source)

Check whether a protocol member is annotated. There are some exceptions that can be left unannotated, like ``__slots__``.

def is_base_class(self, t: TypeInfo, s: TypeInfo) -> bool: (source)

Determine if t is a base class of s (but do not use mro).

def is_class_scope(self) -> bool: (source)

Undocumented

def is_classvar(self, typ: Type) -> bool: (source)

Undocumented

def is_core_builtin_class(self, defn: ClassDef) -> bool: (source)

Undocumented

def is_defined_in_current_module(self, fullname: str|None) -> bool: (source)

Undocumented

def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool: (source)

Does this (analyzed or not) type represent the expected Self type for a method?

def is_final_redefinition(self, kind: int, name: str) -> bool: (source)

Undocumented

def is_final_type(self, typ: Type|None) -> bool: (source)

Undocumented

def is_future_flag_set(self, flag: str) -> bool: (source)

Is the specific __future__ feature imported

def is_global_or_nonlocal(self, name: str) -> bool: (source)

Undocumented

def is_incomplete_namespace(self, fullname: str) -> bool: (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.

def is_initial_mangled_global(self, name: str) -> bool: (source)

Undocumented

def is_local_name(self, name: str) -> bool: (source)

Does name look like reference to a definition in the current module?

def is_mangled_global(self, name: str) -> bool: (source)

Undocumented

def is_missing_module(self, module: str) -> bool: (source)

Undocumented

def is_module_scope(self) -> bool: (source)

Undocumented

def is_nested_within_func_scope(self) -> bool: (source)

Are we underneath a function scope, even if we are in a nested class also?

def is_none_alias(self, node: Expression) -> bool: (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.

def is_overloaded_item(self, node: SymbolNode, statement: Statement) -> bool: (source)

Check whether the function belongs to the overloaded variants

def is_pep_613(self, s: AssignmentStmt) -> bool: (source)

Undocumented

def is_self_member_ref(self, memberexpr: MemberExpr) -> bool: (source)

Does memberexpr to refer to an attribute of self?

def is_textually_before_statement(self, node: SymbolNode) -> bool: (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.

def is_type_ref(self, rv: Expression, bare: bool = False) -> bool: (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().

def is_valid_del_target(self, s: Expression) -> bool: (source)

Undocumented

def leave_class(self): (source)

Restore analyzer state.

def lookup(self, name: str, ctx: Context, suppress_errors: bool = False) -> SymbolTableNode|None: (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.

def lookup_current_scope(self, name: str) -> SymbolTableNode|None: (source)

Undocumented

def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode: (source)

Lookup a symbol by its fully qualified name. Raise an error if not found.

def lookup_fully_qualified_or_none(self, fullname: str) -> SymbolTableNode|None: (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.

def lookup_qualified(self, name: str, ctx: Context, suppress_errors: bool = False) -> SymbolTableNode|None: (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.

def lookup_type_node(self, expr: Expression) -> SymbolTableNode|None: (source)

Undocumented

def make_empty_type_info(self, defn: ClassDef) -> TypeInfo: (source)

Undocumented

def make_name_lvalue_point_to_existing_def(self, lval: NameExpr, explicit_type: bool, is_final: bool): (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.

def make_name_lvalue_var(self, lvalue: NameExpr, kind: int, inferred: bool, has_explicit_value: bool) -> Var: (source)

Return a Var node for an lvalue that is a name expression.

def mark_incomplete(self, name: str, node: Node, becomes_typeinfo: bool = False, module_public: bool = True, module_hidden: bool = 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).

def name_already_defined(self, name: str, ctx: Context, original_ctx: (SymbolTableNode|SymbolNode)|None = None): (source)

Undocumented

def name_not_defined(self, name: str, ctx: Context, namespace: str|None = None): (source)

Undocumented

def named_type(self, fullname: str, args: list[Type]|None = None) -> Instance: (source)

Construct an instance of a builtin type with given type arguments.

def named_type_or_none(self, fullname: str, args: list[Type]|None = None) -> Instance|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.

def object_type(self) -> Instance: (source)

Undocumented

def parse_bool(self, expr: Expression) -> bool|None: (source)

Parse True/False literals.

def parse_dataclass_transform_field_specifiers(self, arg: Expression) -> tuple[str, ...]: (source)

Undocumented

def parse_dataclass_transform_spec(self, call: CallExpr) -> DataclassTransformSpec: (source)

Build a DataclassTransformSpec from the arguments passed to the given call to typing.dataclass_transform.

def parse_str_literal(self, expr: Expression) -> str|None: (source)

Attempt to find the string literal value of the given expression. Returns `None` if no literal value can be found.

def prepare_builtins_namespace(self, file_node: MypyFile): (source)

Add certain special-cased definitions to the builtins module. Some definitions are too special or fundamental to be processed normally from the AST.

def prepare_class_def(self, defn: ClassDef, info: TypeInfo|None = None, custom_names: bool = False): (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).

def prepare_file(self, file_node: MypyFile): (source)

Prepare a freshly parsed file for semantic analysis.

def prepare_method_signature(self, func: FuncDef, info: TypeInfo, has_self_type: bool): (source)

Check basic signature validity and tweak annotation of self/cls argument.

def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]): (source)

Remove dummy alias definitions such as List = TypeAlias(object) from typing. They will be replaced with real aliases when corresponding targets are ready.

def process__all__(self, s: AssignmentStmt): (source)

Export names if argument is a __all__ assignment.

def process__deletable__(self, s: AssignmentStmt): (source)

Undocumented

def process__slots__(self, s: AssignmentStmt): (source)

Processing ``__slots__`` if defined in type. See: https://docs.python.org/3/reference/datamodel.html#slots

def process_final_in_overload(self, defn: OverloadedFuncDef): (source)

Detect the @final status of an overloaded function (and perform checks).

def process_import_over_existing_name(self, imported_id: str, existing_symbol: SymbolTableNode, module_symbol: SymbolTableNode, import_node: ImportBase) -> bool: (source)

Undocumented

def process_imported_symbol(self, node: SymbolTableNode, module_id: str, id: str, imported_id: str, fullname: str, module_public: bool, context: ImportBase): (source)

Undocumented

def process_module_assignment(self, lvals: list[Lvalue], rval: Expression, ctx: AssignmentStmt): (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].

def process_overload_impl(self, defn: OverloadedFuncDef): (source)

Set flags for an overload implementation. Currently, this checks for a trivial body in protocols classes, where it makes the method implicitly abstract.

def process_paramspec_declaration(self, s: AssignmentStmt) -> bool: (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.

def process_placeholder(self, name: str|None, kind: str, ctx: Context, force_progress: bool = False): (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).

def process_static_or_class_method_in_overload(self, defn: OverloadedFuncDef): (source)

Undocumented

def process_type_annotation(self, s: AssignmentStmt): (source)

Analyze type annotation or infer simple literal type.

def process_typevar_declaration(self, s: AssignmentStmt) -> bool: (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.

def process_typevar_parameters(self, args: list[Expression], names: list[str|None], kinds: list[ArgKind], num_values: int, context: Context) -> tuple[int, Type]|None: (source)

Undocumented

def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool: (source)

Checks if s declares a TypeVarTuple; if yes, store it in symbol table. Return True if this looks like a TypeVarTuple (maybe with errors), otherwise return False.

def qualified_name(self, name: str) -> str: (source)

Make qualified name using current module and enclosing class (if any).

def recalculate_metaclass(self, defn: ClassDef, declared_metaclass: Instance|None): (source)

Undocumented

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: AssignmentStmt): (source)

Record minimal necessary information about l.h.s. of a special form. This exists mostly for compatibility with the old semantic analyzer.

def refresh_partial(self, node: (MypyFile|FuncDef)|OverloadedFuncDef, patches: list[tuple[int, Callable[[], None]]], final_iteration: bool, file_node: MypyFile, options: Options, active_type: TypeInfo|None = None): (source)

Refresh a stale target in fine-grained incremental mode.

def refresh_top_level(self, file_node: MypyFile): (source)

Reanalyze a stale module top-level in fine-grained incremental mode.

def remove_unpack_kwargs(self, defn: FuncDef, typ: CallableType) -> CallableType: (source)

Undocumented

def report_hang(self): (source)

Undocumented

def report_missing_module_attribute(self, import_id: str, source_id: str, imported_id: str, module_public: bool, module_hidden: bool, context: Node, add_unknown_imported_symbol: bool = True): (source)

Undocumented

def schedule_patch(self, priority: int, patch: Callable[[], None]): (source)
def set_dummy_mro(self, info: TypeInfo): (source)

Undocumented

def set_future_import_flags(self, module_name: str): (source)

Undocumented

def set_original_def(self, previous: Node|None, new: FuncDef|Decorator) -> bool: (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

def setup_alias_type_vars(self, defn: ClassDef): (source)

Undocumented

def setup_self_type(self): (source)

Setup a (shared) Self type variable for current class. We intentionally don't add it to the class symbol table, so it can be accessed only by mypy and will not cause clashes with user defined names.

def setup_type_vars(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]): (source)

Undocumented

def should_wait_rhs(self, rv: Expression) -> bool: (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.

def store_declared_types(self, lvalue: Lvalue, typ: Type): (source)

Undocumented

def store_final_status(self, s: AssignmentStmt): (source)

If this is a locally valid final declaration, set the corresponding flag on `Var`.

def str_type(self) -> Instance: (source)

Undocumented

def track_incomplete_refs(self) -> Tag: (source)

Return tag that can be used for tracking references to incomplete names.

def translate_dict_call(self, call: CallExpr) -> DictExpr|None: (source)

Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}. For other variants of dict(...), return None.

@contextmanager
def tvar_scope_frame(self, frame: TypeVarLikeScope) -> Iterator[None]: (source)

Undocumented

def type_analyzer(self, *, tvar_scope: TypeVarLikeScope|None = None, allow_tuple_literal: bool = False, allow_unbound_tvars: bool = False, allow_placeholder: bool = False, allow_required: bool = False, allow_param_spec_literals: bool = False, report_invalid_types: bool = True, prohibit_self_type: str|None = None, allow_type_any: bool = False) -> TypeAnalyser: (source)

Undocumented

def unwrap_final(self, s: AssignmentStmt) -> bool: (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.

def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> bool: (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. Return True, if the signature contains typing.Self type, or False otherwise.

def verify_base_classes(self, defn: ClassDef) -> bool: (source)

Undocumented

def visit__promote_expr(self, expr: PromoteExpr): (source)
def visit_as_pattern(self, p: AsPattern): (source)
def visit_assert_stmt(self, s: AssertStmt): (source)
def visit_assert_type_expr(self, expr: AssertTypeExpr): (source)
def visit_assignment_expr(self, s: AssignmentExpr): (source)
def visit_assignment_stmt(self, s: AssignmentStmt): (source)
def visit_await_expr(self, expr: AwaitExpr): (source)
def visit_block(self, b: Block): (source)

Undocumented

def visit_block_maybe(self, b: Block|None): (source)

Undocumented

def visit_break_stmt(self, s: BreakStmt): (source)
def visit_call_expr(self, expr: CallExpr): (source)

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

def visit_cast_expr(self, expr: CastExpr): (source)
def visit_class_def(self, defn: ClassDef): (source)
def visit_class_pattern(self, p: ClassPattern): (source)
def visit_comparison_expr(self, expr: ComparisonExpr): (source)
def visit_conditional_expr(self, expr: ConditionalExpr): (source)
def visit_continue_stmt(self, s: ContinueStmt): (source)
def visit_decorator(self, dec: Decorator): (source)
def visit_del_stmt(self, s: DelStmt): (source)
def visit_dict_expr(self, expr: DictExpr): (source)
def visit_dictionary_comprehension(self, expr: DictionaryComprehension): (source)
def visit_expression_stmt(self, s: ExpressionStmt): (source)
def visit_for_stmt(self, s: ForStmt): (source)
def visit_func_def(self, defn: FuncDef): (source)
def visit_generator_expr(self, expr: GeneratorExpr): (source)
def visit_global_decl(self, g: GlobalDecl): (source)
def visit_if_stmt(self, s: IfStmt): (source)
def visit_import(self, i: Import): (source)

Undocumented

def visit_import_all(self, i: ImportAll): (source)
def visit_import_from(self, imp: ImportFrom): (source)
def visit_index_expr(self, expr: IndexExpr): (source)
def visit_lambda_expr(self, expr: LambdaExpr): (source)
def visit_list_comprehension(self, expr: ListComprehension): (source)
def visit_list_expr(self, expr: ListExpr): (source)
def visit_mapping_pattern(self, p: MappingPattern): (source)
def visit_match_stmt(self, s: MatchStmt): (source)
def visit_member_expr(self, expr: MemberExpr): (source)
def visit_name_expr(self, expr: NameExpr): (source)
def visit_nonlocal_decl(self, d: NonlocalDecl): (source)
def visit_op_expr(self, expr: OpExpr): (source)
def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt): (source)
def visit_or_pattern(self, p: OrPattern): (source)
def visit_overloaded_func_def(self, defn: OverloadedFuncDef): (source)
def visit_raise_stmt(self, s: RaiseStmt): (source)
def visit_return_stmt(self, s: ReturnStmt): (source)
def visit_reveal_expr(self, expr: RevealExpr): (source)
def visit_sequence_pattern(self, p: SequencePattern): (source)
def visit_set_comprehension(self, expr: SetComprehension): (source)
def visit_set_expr(self, expr: SetExpr): (source)
def visit_slice_expr(self, expr: SliceExpr): (source)
def visit_star_expr(self, expr: StarExpr): (source)
def visit_starred_pattern(self, p: StarredPattern): (source)
def visit_super_expr(self, expr: SuperExpr): (source)
def visit_try_stmt(self, s: TryStmt): (source)
def visit_tuple_expr(self, expr: TupleExpr): (source)
def visit_type_application(self, expr: TypeApplication): (source)
def visit_unary_expr(self, expr: UnaryExpr): (source)
def visit_value_pattern(self, p: ValuePattern): (source)
def visit_while_stmt(self, s: WhileStmt): (source)
def visit_with_stmt(self, s: WithStmt): (source)
def visit_yield_expr(self, e: YieldExpr): (source)
def visit_yield_from_expr(self, e: YieldFromExpr): (source)
__deletable__: list[str] = (source)

Undocumented

global_decls: list[set[str]] = (source)

Undocumented

nonlocal_decls: list[set[str]] = (source)

Undocumented

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

Undocumented

all_exports: list = (source)

Undocumented

allow_unbound_tvars: bool = (source)

Undocumented

basic_type_applications = (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

Undocumented

export_map: dict[str, list[str]] = (source)

Undocumented

function_stack: list = (source)

Undocumented

Undocumented

Undocumented

incomplete: bool = (source)

Undocumented

incomplete_namespaces = (source)

Undocumented

incomplete_type_stack: list[bool] = (source)

Undocumented

is_comprehension_stack: list[bool] = (source)

Undocumented

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

Undocumented

Undocumented

progress: bool = (source)

Undocumented

recurse_into_functions: bool = (source)

Undocumented

Undocumented

statement = (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?

def _get_node_for_class_scoped_import(self, name: str, symbol_node: SymbolNode|None, context: Context) -> SymbolNode|None: (source)

Undocumented

_final_iteration = (source)

Undocumented

_is_stub_file = (source)

Undocumented

_is_typeshed_stub_file = (source)

Undocumented

Undocumented