class documentation

class TypeChecker(NodeVisitor[None], CheckerPluginInterface): (source)

View In Hierarchy

Mypy type checker.

Type check mypy source files that have been semantically analyzed.

You must create a separate instance for each source file.

Method __init__ Construct a type checker.
Method accept Type check a node in the given type context.
Method accept​_loop Repeatedly type check a loop body until the frame doesn't change. If exit_condition is set, assume it must be False on exit from the loop.
Method analyze​_async​_iterable​_item​_type Analyse async iterable expression and return iterator and iterator item types.
Method analyze​_container​_item​_type Check if a type is a nominal container of a union of such.
Method analyze​_index​_variables Type check or infer for loop or list comprehension index vars.
Method analyze​_iterable​_item​_type Analyse iterable expression and return iterator and iterator item types.
Method bind​_and​_map​_method Bind self-type and map type variables for a method.
Method check​_​_​_new​_​_​_signature Undocumented
Method check​_​_exit​_​_return​_type Generate error if the return type of __exit__ is problematic.
Method check​_assignment Type check a single assignment: lvalue = rvalue.
Method check​_assignment​_to​_multiple​_lvalues Undocumented
Method check​_assignment​_to​_slots Undocumented
Method check​_async​_with​_item Undocumented
Method check​_compatibility Check if attribute name in base1 is compatible with base2 in multiple inheritance.
Method check​_compatibility​_all​_supers Undocumented
Method check​_compatibility​_classvar​_super Undocumented
Method check​_compatibility​_final​_super Check if an assignment overrides a final attribute in a base class.
Method check​_compatibility​_super Undocumented
Method check​_default​_args Undocumented
Method check​_except​_handler​_test Type check an exception handler test clause.
Method check​_final Check if this assignment does not assign to a final attribute.
Method check​_final​_deletable Undocumented
Method check​_first​_pass Type check the entire file, but defer functions with unresolved references.
Method check​_for​_missing​_annotations Undocumented
Method check​_for​_untyped​_decorator Undocumented
Method check​_func​_def Type check a function definition.
Method check​_func​_item Type check a function.
Method check​_getattr​_method Undocumented
Method check​_if​_final​_var​_override​_writable Check that a final variable doesn't override writeable attribute.
Method check​_import Undocumented
Method check​_incompatible​_property​_override Undocumented
Method check​_indexed​_assignment Type check indexed assignment base[index] = rvalue.
Method check​_init​_subclass Check that keywords in a class definition are valid arguments for __init_subclass__().
Method check​_inplace​_operator​_method Check an inplace operator method such as __iadd__.
Method check​_lvalue Undocumented
Method check​_member​_assignment Type member assignment.
Method check​_method​_or​_accessor​_override​_for​_base Check if method definition is compatible with a base class.
Method check​_method​_override Check if function definition is compatible with base classes.
Method check​_method​_override​_for​_base​_with​_name Check if overriding an attribute name of base with defn is valid.
Method check​_multi​_assignment Check the assignment of one rvalue to a number of lvalues.
Method check​_multi​_assignment​_from​_iterable Undocumented
Method check​_multi​_assignment​_from​_tuple Undocumented
Method check​_multi​_assignment​_from​_union Check assignment to multiple lvalue targets when rvalue type is a Union[...]. For example:
Method check​_multiple​_inheritance Check for multiple inheritance related errors.
Method check​_overlapping​_op​_methods Check for overlapping method and reverse method signatures.
Method check​_overlapping​_overloads Undocumented
Method check​_override Check a method override with given signatures.
Method check​_partial Undocumented
Method check​_protocol​_variance Check that protocol definition is compatible with declared variances of type variables.
Method check​_return​_stmt Undocumented
Method check​_reverse​_op​_method Check a reverse operator method such as __radd__.
Method check​_rvalue​_count​_in​_assignment Undocumented
Method check​_second​_pass Run second or following pass of type checking.
Method check​_setattr​_method Undocumented
Method check​_simple​_assignment Undocumented
Method check​_subtype Generate an error if the subtype is not compatible with supertype.
Method check​_top​_level Check only the top-level of a module, skipping function definitions.
Method check​_type​_alias​_rvalue Undocumented
Method check​_untyped​_after​_decorator Undocumented
Method check​_with​_item Undocumented
Method conditional​_callable​_type​_map Takes in an expression and the current type of the expression.
Method conditional​_type​_map​_with​_intersection Undocumented
Method contains​_none Undocumented
Method defer​_node Defer a node for processing during next type-checking pass.
Method determine​_type​_of​_class​_member Undocumented
Method enter​_attribute​_inference​_context Undocumented
Method enter​_final​_context Store whether the current checked assignment is a final declaration.
Method enter​_partial​_types Enter a new scope for collecting partial types.
Method expand​_typevars Undocumented
Method fail Produce an error message.
Method find​_isinstance​_check Find any isinstance checks (within a chain of ands). Includes implicit and explicit checks for None and calls to callable. Also includes TypeGuard functions.
Method find​_isinstance​_check​_helper Undocumented
Method find​_partial​_types Look for an active partial type scope containing variable.
Method find​_partial​_types​_in​_all​_scopes Look for partial type scope containing variable.
Method find​_type​_equals​_check Narrow types based on any checks of the type type(x) == T
Method fixup​_partial​_type Convert a partial type that we couldn't resolve into something concrete.
Method flatten​_lvalues Undocumented
Method function​_type Undocumented
Method get​_coroutine​_return​_type Undocumented
Method get​_final​_context Check whether we a currently checking a final declaration.
Method get​_generator​_receive​_type Given a declared generator return type (t), return the type its yield receives (tc).
Method get​_generator​_return​_type Given the declared return type of a generator (t), return the type it returns (tr).
Method get​_generator​_yield​_type Given the declared return type of a generator (t), return the type it yields (ty).
Method get​_op​_other​_domain Undocumented
Method get​_types​_from​_except​_handler Helper for check_except_handler_test to retrieve handler types.
Method handle​_cannot​_determine​_type Undocumented
Method handle​_partial​_var​_type Handle a reference to a partial type through a var.
Method in​_checked​_function Should we type-check the current function?
Method infer​_issubclass​_maps Infer type restrictions for an expression in issubclass call.
Method infer​_partial​_type Undocumented
Method infer​_variable​_type Infer the type of initialized variables from initializer type.
Method inference​_error​_fallback​_type Undocumented
Method intersect​_instance​_callable Creates a fake type that represents the intersection of an Instance and a CallableType.
Method intersect​_instances Try creating an ad-hoc intersection of the given instances.
Method is​_assignable​_slot Undocumented
Method is​_async​_generator​_return​_type Is typ a valid type for an async generator?
Method is​_defined​_in​_base​_class Undocumented
Method is​_definition Undocumented
Method is​_forward​_op​_method Undocumented
Method is​_generator​_return​_type Is typ a valid type for a generator/coroutine?
Method is​_raising​_or​_empty Returns 'true' if the given statement either throws an error of some kind or is a no-op.
Method is​_reverse​_op​_method Undocumented
Method is​_trivial​_body Returns 'true' if the given body is "trivial" -- if it contains just a "pass", "..." (ellipsis), or "raise NotImplementedError()". A trivial body may also start with a statement containing just a string (e.g. a docstring).
Method is​_unsafe​_overlapping​_op Undocumented
Method is​_valid​_defaultdict​_partial​_value​_type Check if t can be used as the basis for a partial defaultdict value type.
Method is​_writable​_attribute Check if an attribute is writable
Method iterable​_item​_type Undocumented
Method lookup Look up a definition from the symbol table with the given name.
Method lookup​_qualified Undocumented
Method lookup​_typeinfo Undocumented
Method lvalue​_type​_for​_inference Undocumented
Method lvalue​_type​_from​_base For a NameExpr that is part of a class, walk all base classes and try to find the first class that defines a Type for the same name.
Method make​_fake​_callable Produce a new type that makes type Callable with a generic callable type.
Method make​_fake​_typeinfo Undocumented
Method named​_generic​_type Return an instance with the given name and type arguments.
Method named​_type Return an instance type with given name and implicit Any type args.
Method note Produce a note.
Method partition​_by​_callable Partitions a type into callable subtypes and uncallable subtypes.
Method propagate​_up​_typemap​_info Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types.
Method push​_type​_map Undocumented
Method refine​_away​_none​_in​_comparison Produces conditional type maps refining away None in an identity/equality chain.
Method refine​_identity​_comparison​_expression Produce conditional type maps refining expressions by an identity/equality comparison.
Method refine​_parent​_types Checks if the given expr is a 'lookup operation' into a union and iteratively refines the parent types based on the 'expr_type'.
Method reset Cleanup stale state that might be left over from a typechecking run.
Method set​_inference​_error​_fallback​_type Store best known type for variable if type inference failed.
Method set​_inferred​_type Store inferred variable type.
Method should​_report​_unreachable​_issues Undocumented
Method should​_suppress​_optional​_error Undocumented
Method split​_around​_star Splits a list of items in three to match another list of length 'length' that contains a starred expression at 'star_index' in the following way:
Method store​_type Store the type of a node in the type map.
Method str​_type Return instance type 'str'.
Method temp​_node Create a temporary node with the given, fixed type.
Method try​_infer​_partial​_generic​_type​_from​_assignment Try to infer a precise type for partial generic type from assignment.
Method try​_infer​_partial​_type​_from​_indexed​_assignment Undocumented
Method type​_check​_raise Undocumented
Method type​_is​_iterable Undocumented
Method type​_type Return instance type 'type'.
Method visit​_assert​_stmt Undocumented
Method visit​_assignment​_stmt Type check an assignment statement.
Method visit​_block Undocumented
Method visit​_break​_stmt Undocumented
Method visit​_class​_def Type check a class definition.
Method visit​_continue​_stmt Undocumented
Method visit​_decorator Undocumented
Method visit​_del​_stmt Undocumented
Method visit​_expression​_stmt Undocumented
Method visit​_for​_stmt Type check a for statement.
Method visit​_func​_def Undocumented
Method visit​_if​_stmt Type check an if statement.
Method visit​_import Undocumented
Method visit​_import​_all Undocumented
Method visit​_import​_from Undocumented
Method visit​_operator​_assignment​_stmt Type check an operator assignment statement, e.g. x += 1.
Method visit​_overloaded​_func​_def Undocumented
Method visit​_print​_stmt Undocumented
Method visit​_raise​_stmt Type check a raise statement.
Method visit​_return​_stmt Type check a return statement.
Method visit​_try​_stmt Type check a try statement.
Method visit​_try​_without​_finally Type check a try statement, ignoring the finally block.
Method visit​_while​_stmt Type check a while statement.
Method visit​_with​_stmt Undocumented
Constant partial​_type​_augmented​_ops Undocumented
Instance Variable binder Undocumented
Instance Variable current​_node​_deferred Undocumented
Instance Variable deferred​_nodes Undocumented
Instance Variable dynamic​_funcs Undocumented
Instance Variable errors Undocumented
Instance Variable expr​_checker Undocumented
Instance Variable globals Undocumented
Instance Variable inferred​_attribute​_types Undocumented
Instance Variable is​_stub Undocumented
Instance Variable is​_typeshed​_stub Undocumented
Instance Variable module​_refs Undocumented
Instance Variable modules Undocumented
Instance Variable msg Undocumented
Instance Variable no​_partial​_types Undocumented
Instance Variable options Undocumented
Instance Variable partial​_reported Undocumented
Instance Variable partial​_types Undocumented
Instance Variable pass​_num Undocumented
Instance Variable path Undocumented
Instance Variable plugin Undocumented
Instance Variable recurse​_into​_functions Undocumented
Instance Variable return​_types Undocumented
Instance Variable scope Undocumented
Instance Variable suppress​_none​_errors Undocumented
Instance Variable tree Undocumented
Instance Variable tscope Undocumented
Instance Variable type​_map Undocumented
Instance Variable var​_decl​_frames Undocumented
Property type​_context Return the type context of the plugin
Method _check​_for​_truthy​_type Undocumented
Method _is​_truthy​_type Undocumented
Method _visit​_func​_def Type check a function definition.
Method _visit​_overloaded​_func​_def Undocumented
Instance Variable _is​_final​_def Undocumented
def __init__(self, errors, modules, options, tree, path, plugin): (source)

Construct a type checker.

Use errors to report type check errors.

Parameters
errors:ErrorsUndocumented
modules:Dict[str, MypyFile]Undocumented
options:OptionsUndocumented
tree:MypyFileUndocumented
path:strUndocumented
plugin:PluginUndocumented
def accept(self, stmt): (source)
Type check a node in the given type context.
Parameters
stmt:StatementUndocumented
def accept_loop(self, body, else_body=None, *, exit_condition=None): (source)

Repeatedly type check a loop body until the frame doesn't change. If exit_condition is set, assume it must be False on exit from the loop.

Then check the else_body.

Parameters
body:StatementUndocumented
else​_body:Optional[Statement]Undocumented
exit​_condition:Optional[Expression]Undocumented
def analyze_async_iterable_item_type(self, expr): (source)
Analyse async iterable expression and return iterator and iterator item types.
Parameters
expr:ExpressionUndocumented
Returns
Tuple[Type, Type]Undocumented
def analyze_container_item_type(self, typ): (source)

Check if a type is a nominal container of a union of such.

Return the corresponding container item type.

Parameters
typ:TypeUndocumented
Returns
Optional[Type]Undocumented
def analyze_index_variables(self, index, item_type, infer_lvalue_type, context): (source)
Type check or infer for loop or list comprehension index vars.
Parameters
index:ExpressionUndocumented
item​_type:TypeUndocumented
infer​_lvalue​_type:boolUndocumented
context:ContextUndocumented
def analyze_iterable_item_type(self, expr): (source)
Analyse iterable expression and return iterator and iterator item types.
Parameters
expr:ExpressionUndocumented
Returns
Tuple[Type, Type]Undocumented
def bind_and_map_method(self, sym, typ, sub_info, super_info): (source)

Bind self-type and map type variables for a method.

Arguments:
sym: a symbol that points to method definition typ: method type on the definition sub_info: class where the method is used super_info: class where the method was defined
Parameters
sym:SymbolTableNodeUndocumented
typ:FunctionLikeUndocumented
sub​_info:TypeInfoUndocumented
super​_info:TypeInfoUndocumented
Returns
FunctionLikeUndocumented
def check___new___signature(self, fdef, typ): (source)

Undocumented

Parameters
fdef:FuncDefUndocumented
typ:CallableTypeUndocumented
def check__exit__return_type(self, defn): (source)

Generate error if the return type of __exit__ is problematic.

If __exit__ always returns False but the return type is declared as bool, mypy thinks that a with statement may "swallow" exceptions even though this is not the case, resulting in invalid reachability inference.

Parameters
defn:FuncItemUndocumented
def check_assignment(self, lvalue, rvalue, infer_lvalue_type=True, new_syntax=False): (source)
Type check a single assignment: lvalue = rvalue.
Parameters
lvalue:LvalueUndocumented
rvalue:ExpressionUndocumented
infer​_lvalue​_type:boolUndocumented
new​_syntax:boolUndocumented
def check_assignment_to_multiple_lvalues(self, lvalues, rvalue, context, infer_lvalue_type=True): (source)

Undocumented

Parameters
lvalues:List[Lvalue]Undocumented
rvalue:ExpressionUndocumented
context:ContextUndocumented
infer​_lvalue​_type:boolUndocumented
def check_assignment_to_slots(self, lvalue): (source)

Undocumented

Parameters
lvalue:LvalueUndocumented
def check_async_with_item(self, expr, target, infer_lvalue_type): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
target:Optional[Expression]Undocumented
infer​_lvalue​_type:boolUndocumented
Returns
TypeUndocumented
def check_compatibility(self, name, base1, base2, ctx): (source)

Check if attribute name in base1 is compatible with base2 in multiple inheritance.

Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have a direct subclass relationship (i.e., the compatibility requirement only derives from multiple inheritance).

This check verifies that a definition taken from base1 (and mapped to the current class ctx), is type compatible with the definition taken from base2 (also mapped), so that unsafe subclassing like this can be detected:

class A(Generic[T]):
def foo(self, x: T) -> None: ...
class B:
def foo(self, x: str) -> None: ...

class C(B, A[int]): ... # this is unsafe because...

x: A[int] = C() x.foo # ...runtime type is (str) -> None, while static type is (int) -> None

Parameters
name:strUndocumented
base1:TypeInfoUndocumented
base2:TypeInfoUndocumented
ctx:TypeInfoUndocumented
def check_compatibility_all_supers(self, lvalue, lvalue_type, rvalue): (source)

Undocumented

Parameters
lvalue:RefExprUndocumented
lvalue​_type:Optional[Type]Undocumented
rvalue:ExpressionUndocumented
Returns
boolUndocumented
def check_compatibility_classvar_super(self, node, base, base_node): (source)

Undocumented

Parameters
node:VarUndocumented
base:TypeInfoUndocumented
base​_node:Optional[Node]Undocumented
Returns
boolUndocumented
def check_compatibility_final_super(self, node, base, base_node): (source)

Check if an assignment overrides a final attribute in a base class.

This only checks situations where either a node in base class is not a variable but a final method, or where override is explicitly declared as final. In these cases we give a more detailed error message. In addition, we check that a final variable doesn't override writeable attribute, which is not safe.

Other situations are checked in check_final().

Parameters
node:VarUndocumented
base:TypeInfoUndocumented
base​_node:Optional[Node]Undocumented
Returns
boolUndocumented
def check_compatibility_super(self, lvalue, lvalue_type, rvalue, base, base_type, base_node): (source)

Undocumented

Parameters
lvalue:RefExprUndocumented
lvalue​_type:Optional[Type]Undocumented
rvalue:ExpressionUndocumented
base:TypeInfoUndocumented
base​_type:TypeUndocumented
base​_node:NodeUndocumented
Returns
boolUndocumented
def check_default_args(self, item, body_is_trivial): (source)

Undocumented

Parameters
item:FuncItemUndocumented
body​_is​_trivial:boolUndocumented
def check_except_handler_test(self, n): (source)
Type check an exception handler test clause.
Parameters
n:ExpressionUndocumented
Returns
TypeUndocumented
def check_final(self, s): (source)

Check if this assignment does not assign to a final attribute.

This function performs the check only for name assignments at module and class scope. The assignments to obj.attr and Cls.attr are checked in checkmember.py.

Parameters
s:Union[AssignmentStmt, OperatorAssignmentStmt, AssignmentExpr]Undocumented
def check_final_deletable(self, typ): (source)

Undocumented

Parameters
typ:TypeInfoUndocumented
def check_first_pass(self): (source)

Type check the entire file, but defer functions with unresolved references.

Unresolved references are forward references to variables whose types haven't been inferred yet. They may occur later in the same file or in a different file that's being processed later (usually due to an import cycle).

Deferred functions will be processed by check_second_pass().

def check_for_missing_annotations(self, fdef): (source)

Undocumented

Parameters
fdef:FuncItemUndocumented
def check_for_untyped_decorator(self, func, dec_type, dec_expr): (source)

Undocumented

Parameters
func:FuncDefUndocumented
dec​_type:TypeUndocumented
dec​_expr:ExpressionUndocumented
def check_func_def(self, defn, typ, name): (source)
Type check a function definition.
Parameters
defn:FuncItemUndocumented
typ:CallableTypeUndocumented
name:Optional[str]Undocumented
def check_func_item(self, defn, type_override=None, name=None): (source)

Type check a function.

If type_override is provided, use it as the function type.

Parameters
defn:FuncItemUndocumented
type​_override:Optional[CallableType]Undocumented
name:Optional[str]Undocumented
def check_getattr_method(self, typ, context, name): (source)

Undocumented

Parameters
typ:TypeUndocumented
context:ContextUndocumented
name:strUndocumented
def check_if_final_var_override_writable(self, name, base_node, ctx): (source)

Check that a final variable doesn't override writeable attribute.

This is done to prevent situations like this:
class C:
attr = 1
class D(C):
attr: Final = 2

x: C = D() x.attr = 3 # Oops!

Parameters
name:strUndocumented
base​_node:Optional[Node]Undocumented
ctx:ContextUndocumented
def check_import(self, node): (source)

Undocumented

Parameters
node:ImportBaseUndocumented
def check_incompatible_property_override(self, e): (source)

Undocumented

Parameters
e:DecoratorUndocumented
def check_indexed_assignment(self, lvalue, rvalue, context): (source)

Type check indexed assignment base[index] = rvalue.

The lvalue argument is the base[index] expression.

Parameters
lvalue:IndexExprUndocumented
rvalue:ExpressionUndocumented
context:ContextUndocumented
def check_init_subclass(self, defn): (source)

Check that keywords in a class definition are valid arguments for __init_subclass__().

In this example:
1 class Base: 2 def __init_subclass__(cls, thing: int): 3 pass 4 class Child(Base, thing=5): 5 def __init_subclass__(cls): 6 pass 7 Child()

Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here. Child.__init_subclass__ is never called.

Parameters
defn:ClassDefUndocumented
def check_inplace_operator_method(self, defn): (source)

Check an inplace operator method such as __iadd__.

They cannot arbitrarily overlap with __add__.

Parameters
defn:FuncBaseUndocumented
def check_lvalue(self, lvalue): (source)

Undocumented

Parameters
lvalue:LvalueUndocumented
Returns
Tuple[Optional[Type], Optional[IndexExpr], Optional[Var]]Undocumented
def check_member_assignment(self, instance_type, attribute_type, rvalue, context): (source)

Type member assignment.

This defers to check_simple_assignment, unless the member expression is a descriptor, in which case this checks descriptor semantics as well.

Return the inferred rvalue_type, inferred lvalue_type, and whether to use the binder for this assignment.

Note: this method exists here and not in checkmember.py, because we need to take care about interaction between binder and __set__().

Parameters
instance​_type:TypeUndocumented
attribute​_type:TypeUndocumented
rvalue:ExpressionUndocumented
context:ContextUndocumented
Returns
Tuple[Type, Type, bool]Undocumented
def check_method_or_accessor_override_for_base(self, defn, base): (source)

Check if method definition is compatible with a base class.

Return True if the node was deferred because one of the corresponding superclass nodes is not ready.

Parameters
defn:Union[FuncDef, OverloadedFuncDef, Decorator]Undocumented
base:TypeInfoUndocumented
Returns
boolUndocumented
def check_method_override(self, defn): (source)

Check if function definition is compatible with base classes.

This may defer the method if a signature is not available in at least one base class.

Parameters
defn:Union[FuncDef, OverloadedFuncDef, Decorator]Undocumented
def check_method_override_for_base_with_name(self, defn, name, base): (source)

Check if overriding an attribute name of base with defn is valid.

Return True if the supertype node was not analysed yet, and defn was deferred.

Parameters
defn:Union[FuncDef, OverloadedFuncDef, Decorator]Undocumented
name:strUndocumented
base:TypeInfoUndocumented
Returns
boolUndocumented
def check_multi_assignment(self, lvalues, rvalue, context, infer_lvalue_type=True, rv_type=None, undefined_rvalue=False): (source)
Check the assignment of one rvalue to a number of lvalues.
Parameters
lvalues:List[Lvalue]Undocumented
rvalue:ExpressionUndocumented
context:ContextUndocumented
infer​_lvalue​_type:boolUndocumented
rv​_type:Optional[Type]Undocumented
undefined​_rvalue:boolUndocumented
def check_multi_assignment_from_iterable(self, lvalues, rvalue_type, context, infer_lvalue_type=True): (source)

Undocumented

Parameters
lvalues:List[Lvalue]Undocumented
rvalue​_type:TypeUndocumented
context:ContextUndocumented
infer​_lvalue​_type:boolUndocumented
def check_multi_assignment_from_tuple(self, lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type=True): (source)

Undocumented

Parameters
lvalues:List[Lvalue]Undocumented
rvalue:ExpressionUndocumented
rvalue​_type:TupleTypeUndocumented
context:ContextUndocumented
undefined​_rvalue:boolUndocumented
infer​_lvalue​_type:boolUndocumented
def check_multi_assignment_from_union(self, lvalues, rvalue, rvalue_type, context, infer_lvalue_type): (source)

Check assignment to multiple lvalue targets when rvalue type is a Union[...]. For example:

t: Union[Tuple[int, int], Tuple[str, str]] x, y = t reveal_type(x) # Union[int, str]

The idea in this case is to process the assignment for every item of the union. Important note: the types are collected in two places, 'union_types' contains inferred types for first assignments, 'assignments' contains the narrowed types for binder.

Parameters
lvalues:List[Expression]Undocumented
rvalue:ExpressionUndocumented
rvalue​_type:UnionTypeUndocumented
context:ContextUndocumented
infer​_lvalue​_type:boolUndocumented
def check_multiple_inheritance(self, typ): (source)
Check for multiple inheritance related errors.
Parameters
typ:TypeInfoUndocumented
def check_overlapping_op_methods(self, reverse_type, reverse_name, reverse_class, forward_type, forward_name, forward_base, context): (source)

Check for overlapping method and reverse method signatures.

This function assumes that:

  • The reverse method has valid argument count and kinds.

  • If the reverse operator method accepts some argument of type X, the forward operator method also belong to class X.

    For example, if we have the reverse operator A.__radd__(B), then the corresponding forward operator must have the type B.__add__(...).

Parameters
reverse​_type:CallableTypeUndocumented
reverse​_name:strUndocumented
reverse​_class:TypeInfoUndocumented
forward​_type:TypeUndocumented
forward​_name:strUndocumented
forward​_base:TypeUndocumented
context:ContextUndocumented
def check_overlapping_overloads(self, defn): (source)

Undocumented

Parameters
defn:OverloadedFuncDefUndocumented
def check_override(self, override, original, name, name_in_super, supertype, original_class_or_static, override_class_or_static, node): (source)

Check a method override with given signatures.

Arguments:

override: The signature of the overriding method. original: The signature of the original supertype method. name: The name of the subtype. This and the next argument are

only used for generating error messages.

supertype: The name of the supertype.

Parameters
override:FunctionLikeUndocumented
original:FunctionLikeUndocumented
name:strUndocumented
name​_in​_super:strUndocumented
supertype:strUndocumented
original​_class​_or​_static:boolUndocumented
override​_class​_or​_static:boolUndocumented
node:ContextUndocumented
def check_partial(self, node): (source)

Undocumented

Parameters
node:Union[DeferredNodeType, FineGrainedDeferredNodeType]Undocumented
def check_protocol_variance(self, defn): (source)

Check that protocol definition is compatible with declared variances of type variables.

Note that we also prohibit declaring protocol classes as invariant if they are actually covariant/contravariant, since this may break transitivity of subtyping, see PEP 544.

Parameters
defn:ClassDefUndocumented
def check_return_stmt(self, s): (source)

Undocumented

Parameters
s:ReturnStmtUndocumented
def check_reverse_op_method(self, defn, reverse_type, reverse_name, context): (source)
Check a reverse operator method such as __radd__.
Parameters
defn:FuncItemUndocumented
reverse​_type:CallableTypeUndocumented
reverse​_name:strUndocumented
context:ContextUndocumented
def check_rvalue_count_in_assignment(self, lvalues, rvalue_count, context): (source)

Undocumented

Parameters
lvalues:List[Lvalue]Undocumented
rvalue​_count:intUndocumented
context:ContextUndocumented
Returns
boolUndocumented
def check_second_pass(self, todo=None): (source)

Run second or following pass of type checking.

This goes through deferred nodes, returning True if there were any.

Parameters
todo:Optional[Sequence[Union[DeferredNode, FineGrainedDeferredNode]]]Undocumented
Returns
boolUndocumented
def check_setattr_method(self, typ, context): (source)

Undocumented

Parameters
typ:TypeUndocumented
context:ContextUndocumented
def check_simple_assignment(self, lvalue_type, rvalue, context, msg=message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, lvalue_name='variable', rvalue_name='expression', *, code=None): (source)

Undocumented

Parameters
lvalue​_type:Optional[Type]Undocumented
rvalue:ExpressionUndocumented
context:ContextUndocumented
msg:strUndocumented
lvalue​_name:strUndocumented
rvalue​_name:strUndocumented
code:Optional[ErrorCode]Undocumented
Returns
TypeUndocumented
def check_subtype(self, subtype, supertype, context, msg=message_registry.INCOMPATIBLE_TYPES, subtype_label=None, supertype_label=None, *, code=None, outer_context=None): (source)
Generate an error if the subtype is not compatible with supertype.
Parameters
subtype:TypeUndocumented
supertype:TypeUndocumented
context:ContextUndocumented
msg:Union[str, ErrorMessage]Undocumented
subtype​_label:Optional[str]Undocumented
supertype​_label:Optional[str]Undocumented
code:Optional[ErrorCode]Undocumented
outer​_context:Optional[Context]Undocumented
Returns
boolUndocumented
def check_top_level(self, node): (source)
Check only the top-level of a module, skipping function definitions.
Parameters
node:MypyFileUndocumented
def check_type_alias_rvalue(self, s): (source)

Undocumented

Parameters
s:AssignmentStmtUndocumented
def check_untyped_after_decorator(self, typ, func): (source)

Undocumented

Parameters
typ:TypeUndocumented
func:FuncDefUndocumented
def check_with_item(self, expr, target, infer_lvalue_type): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
target:Optional[Expression]Undocumented
infer​_lvalue​_type:boolUndocumented
Returns
TypeUndocumented
def conditional_callable_type_map(self, expr, current_type): (source)

Takes in an expression and the current type of the expression.

Returns a 2-tuple: The first element is a map from the expression to the restricted type if it were callable. The second element is a map from the expression to the type it would hold if it weren't callable.

Parameters
expr:ExpressionUndocumented
current​_type:Optional[Type]Undocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def conditional_type_map_with_intersection(self, expr, expr_type, type_ranges): (source)

Undocumented

Parameters
expr:ExpressionUndocumented
expr​_type:TypeUndocumented
type​_ranges:Optional[List[TypeRange]]Undocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def contains_none(self, t): (source)

Undocumented

Parameters
t:TypeUndocumented
Returns
boolUndocumented
def defer_node(self, node, enclosing_class): (source)

Defer a node for processing during next type-checking pass.

Args:
node: function/method being deferred enclosing_class: for methods, the class where the method is defined

NOTE: this can't handle nested functions/methods.

Parameters
node:DeferredNodeTypeUndocumented
enclosing​_class:Optional[TypeInfo]Undocumented
def determine_type_of_class_member(self, sym): (source)

Undocumented

Parameters
sym:SymbolTableNodeUndocumented
Returns
Optional[Type]Undocumented
@contextmanager
def enter_attribute_inference_context(self): (source)

Undocumented

Returns
Iterator[None]Undocumented
@contextmanager
def enter_final_context(self, is_final_def): (source)
Store whether the current checked assignment is a final declaration.
Parameters
is​_final​_def:boolUndocumented
Returns
Iterator[None]Undocumented
@contextmanager
def enter_partial_types(self, *, is_function=False, is_class=False): (source)

Enter a new scope for collecting partial types.

Also report errors for (some) variables which still have partial types, i.e. we couldn't infer a complete type.

Parameters
is​_function:boolUndocumented
is​_class:boolUndocumented
Returns
Iterator[None]Undocumented
def expand_typevars(self, defn, typ): (source)

Undocumented

Parameters
defn:FuncItemUndocumented
typ:CallableTypeUndocumented
Returns
List[Tuple[FuncItem, CallableType]]Undocumented
def fail(self, msg, context, *, code=None): (source)
Produce an error message.
Parameters
msg:Union[str, ErrorMessage]Undocumented
context:ContextUndocumented
code:Optional[ErrorCode]Undocumented
def find_isinstance_check(self, node): (source)

Find any isinstance checks (within a chain of ands). Includes implicit and explicit checks for None and calls to callable. Also includes TypeGuard functions.

Return value is a map of variables to their types if the condition is true and a map of variables to their types if the condition is false.

If either of the values in the tuple is None, then that particular branch can never occur.

May return {}, {}. Can return None, None in situations involving NoReturn.

Parameters
node:ExpressionUndocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def find_isinstance_check_helper(self, node): (source)

Undocumented

Parameters
node:ExpressionUndocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def find_partial_types(self, var): (source)

Look for an active partial type scope containing variable.

A scope is active if assignments in the current context can refine a partial type originally defined in the scope. This is affected by the local_partial_types configuration option.

Parameters
var:VarUndocumented
Returns
Optional[Dict[Var, Context]]Undocumented
def find_partial_types_in_all_scopes(self, var): (source)

Look for partial type scope containing variable.

Return tuple (is the scope active, is the scope a local scope, scope).

Parameters
var:VarUndocumented
Returns
Tuple[bool, bool, Optional[Dict[Var, Context]]]Undocumented
def find_type_equals_check(self, node, expr_indices): (source)

Narrow types based on any checks of the type type(x) == T

Args:

node: The node that might contain the comparison expr_indices: The list of indices of expressions in node that are being

compared
Parameters
node:ComparisonExprUndocumented
expr​_indices:List[int]Undocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def fixup_partial_type(self, typ): (source)

Convert a partial type that we couldn't resolve into something concrete.

This means, for None we make it Optional[Any], and for anything else we fill in all of the type arguments with Any.

Parameters
typ:TypeUndocumented
Returns
TypeUndocumented
def flatten_lvalues(self, lvalues): (source)

Undocumented

Parameters
lvalues:List[Expression]Undocumented
Returns
List[Expression]Undocumented
def function_type(self, func): (source)

Undocumented

Parameters
func:FuncBaseUndocumented
Returns
FunctionLikeUndocumented
def get_coroutine_return_type(self, return_type): (source)

Undocumented

Parameters
return​_type:TypeUndocumented
Returns
TypeUndocumented
def get_final_context(self): (source)
Check whether we a currently checking a final declaration.
Returns
boolUndocumented
def get_generator_receive_type(self, return_type, is_coroutine): (source)
Given a declared generator return type (t), return the type its yield receives (tc).
Parameters
return​_type:TypeUndocumented
is​_coroutine:boolUndocumented
Returns
TypeUndocumented
def get_generator_return_type(self, return_type, is_coroutine): (source)
Given the declared return type of a generator (t), return the type it returns (tr).
Parameters
return​_type:TypeUndocumented
is​_coroutine:boolUndocumented
Returns
TypeUndocumented
def get_generator_yield_type(self, return_type, is_coroutine): (source)
Given the declared return type of a generator (t), return the type it yields (ty).
Parameters
return​_type:TypeUndocumented
is​_coroutine:boolUndocumented
Returns
TypeUndocumented
def get_op_other_domain(self, tp): (source)

Undocumented

Parameters
tp:FunctionLikeUndocumented
Returns
Optional[Type]Undocumented
def get_types_from_except_handler(self, typ, n): (source)
Helper for check_except_handler_test to retrieve handler types.
Parameters
typ:TypeUndocumented
n:ExpressionUndocumented
Returns
List[Type]Undocumented
def handle_cannot_determine_type(self, name, context): (source)

Undocumented

Parameters
name:strUndocumented
context:ContextUndocumented
def handle_partial_var_type(self, typ, is_lvalue, node, context): (source)

Handle a reference to a partial type through a var.

(Used by checkexpr and checkmember.)

Parameters
typ:PartialTypeUndocumented
is​_lvalue:boolUndocumented
node:VarUndocumented
context:ContextUndocumented
Returns
TypeUndocumented
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 infer_issubclass_maps(self, node, expr, type_map): (source)
Infer type restrictions for an expression in issubclass call.
Parameters
node:CallExprUndocumented
expr:ExpressionUndocumented
type​_map:Dict[Expression, Type]Undocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def infer_partial_type(self, name, lvalue, init_type): (source)

Undocumented

Parameters
name:VarUndocumented
lvalue:LvalueUndocumented
init​_type:TypeUndocumented
Returns
boolUndocumented
def infer_variable_type(self, name, lvalue, init_type, context): (source)
Infer the type of initialized variables from initializer type.
Parameters
name:VarUndocumented
lvalue:LvalueUndocumented
init​_type:TypeUndocumented
context:ContextUndocumented
def inference_error_fallback_type(self, type): (source)

Undocumented

Parameters
type:TypeUndocumented
Returns
TypeUndocumented
def intersect_instance_callable(self, typ, callable_type): (source)

Creates a fake type that represents the intersection of an Instance and a CallableType.

It operates by creating a bare-minimum dummy TypeInfo that subclasses type and adds a __call__ method matching callable_type.

Parameters
typ:InstanceUndocumented
callable​_type:CallableTypeUndocumented
Returns
InstanceUndocumented
def intersect_instances(self, instances, ctx): (source)

Try creating an ad-hoc intersection of the given instances.

Note that this function does not try and create a full-fledged intersection type. Instead, it returns an instance of a new ad-hoc subclass of the given instances.

This is mainly useful when you need a way of representing some theoretical subclass of the instances the user may be trying to use the generated intersection can serve as a placeholder.

This function will create a fresh subclass every time you call it, even if you pass in the exact same arguments. So this means calling self.intersect_intersection([inst_1, inst_2], ctx) twice will result in instances of two distinct subclasses of inst_1 and inst_2.

This is by design: we want each ad-hoc intersection to be unique since they're supposed represent some other unknown subclass.

Returns None if creating the subclass is impossible (e.g. due to MRO errors or incompatible signatures). If we do successfully create a subclass, its TypeInfo will automatically be added to the global scope.

Parameters
instances:Tuple[Instance, Instance]Undocumented
ctx:ContextUndocumented
Returns
Optional[Instance]Undocumented
def is_assignable_slot(self, lvalue, typ): (source)

Undocumented

Parameters
lvalue:LvalueUndocumented
typ:Optional[Type]Undocumented
Returns
boolUndocumented
def is_async_generator_return_type(self, typ): (source)

Is typ a valid type for an async generator?

True if typ is a supertype of AsyncGenerator.

Parameters
typ:TypeUndocumented
Returns
boolUndocumented
def is_defined_in_base_class(self, var): (source)

Undocumented

Parameters
var:VarUndocumented
Returns
boolUndocumented
def is_definition(self, s): (source)

Undocumented

Parameters
s:LvalueUndocumented
Returns
boolUndocumented
def is_forward_op_method(self, method_name): (source)

Undocumented

Parameters
method​_name:strUndocumented
Returns
boolUndocumented
def is_generator_return_type(self, typ, is_coroutine): (source)

Is typ a valid type for a generator/coroutine?

True if typ is a supertype of Generator or Awaitable. Also true it it's exactly AwaitableGenerator (modulo type parameters).

Parameters
typ:TypeUndocumented
is​_coroutine:boolUndocumented
Returns
boolUndocumented
def is_raising_or_empty(self, s): (source)

Returns 'true' if the given statement either throws an error of some kind or is a no-op.

We use this function mostly while handling the '--warn-unreachable' flag. When that flag is present, we normally report an error on any unreachable statement. But if that statement is just something like a 'pass' or a just-in-case 'assert False', reporting an error would be annoying.

Parameters
s:StatementUndocumented
Returns
boolUndocumented
def is_reverse_op_method(self, method_name): (source)

Undocumented

Parameters
method​_name:strUndocumented
Returns
boolUndocumented
def is_trivial_body(self, block): (source)

Returns 'true' if the given body is "trivial" -- if it contains just a "pass", "..." (ellipsis), or "raise NotImplementedError()". A trivial body may also start with a statement containing just a string (e.g. a docstring).

Note: functions that raise other kinds of exceptions do not count as "trivial". We use this function to help us determine when it's ok to relax certain checks on body, but functions that raise arbitrary exceptions are more likely to do non-trivial work. For example:

def halt(self, reason: str = ...) -> NoReturn:
raise MyCustomError("Fatal error: " + reason, self.line, self.context)

A function that raises just NotImplementedError is much less likely to be this complex.

Parameters
block:BlockUndocumented
Returns
boolUndocumented
def is_unsafe_overlapping_op(self, forward_item, forward_base, reverse_type): (source)

Undocumented

Parameters
forward​_item:CallableTypeUndocumented
forward​_base:TypeUndocumented
reverse​_type:CallableTypeUndocumented
Returns
boolUndocumented
def is_valid_defaultdict_partial_value_type(self, t): (source)

Check if t can be used as the basis for a partial defaultdict value type.

Examples:

  • t is 'int' --> True
  • t is 'list[<nothing>]' --> True
  • t is 'dict[...]' --> False (only generic types with a single type argument supported)
Parameters
t:ProperTypeUndocumented
Returns
boolUndocumented
def is_writable_attribute(self, node): (source)
Check if an attribute is writable
Parameters
node:NodeUndocumented
Returns
boolUndocumented
def iterable_item_type(self, instance): (source)

Undocumented

Parameters
instance:InstanceUndocumented
Returns
TypeUndocumented
def lookup(self, name): (source)
Look up a definition from the symbol table with the given name.
Parameters
name:strUndocumented
Returns
SymbolTableNodeUndocumented
def lookup_qualified(self, name): (source)

Undocumented

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

Undocumented

Parameters
fullname:strUndocumented
Returns
TypeInfoUndocumented
def lvalue_type_for_inference(self, lvalues, rvalue_type): (source)

Undocumented

Parameters
lvalues:List[Lvalue]Undocumented
rvalue​_type:TupleTypeUndocumented
Returns
TypeUndocumented
def lvalue_type_from_base(self, expr_node, base): (source)
For a NameExpr that is part of a class, walk all base classes and try to find the first class that defines a Type for the same name.
Parameters
expr​_node:VarUndocumented
base:TypeInfoUndocumented
Returns
Tuple[Optional[Type], Optional[Node]]Undocumented
def make_fake_callable(self, typ): (source)
Produce a new type that makes type Callable with a generic callable type.
Parameters
typ:InstanceUndocumented
Returns
InstanceUndocumented
def make_fake_typeinfo(self, curr_module_fullname, class_gen_name, class_short_name, bases): (source)

Undocumented

Parameters
curr​_module​_fullname:strUndocumented
class​_gen​_name:strUndocumented
class​_short​_name:strUndocumented
bases:List[Instance]Undocumented
Returns
Tuple[ClassDef, TypeInfo]Undocumented
def named_generic_type(self, name, args): (source)

Return an instance with the given name and type arguments.

Assume that the number of arguments is correct. Assume that the name refers to a compatible generic type.

Parameters
name:strUndocumented
args:List[Type]Undocumented
Returns
InstanceUndocumented
def named_type(self, name): (source)

Return an instance type with given name and implicit Any type args.

For example, named_type('builtins.object') produces the 'object' type.

Parameters
name:strUndocumented
Returns
InstanceUndocumented
def note(self, msg, context, offset=0, *, code=None): (source)
Produce a note.
Parameters
msg:strUndocumented
context:ContextUndocumented
offset:intUndocumented
code:Optional[ErrorCode]Undocumented
def partition_by_callable(self, typ, unsound_partition): (source)

Partitions a type into callable subtypes and uncallable subtypes.

Thus, given: callables, uncallables = partition_by_callable(type)

If we assert callable(type) then type has type Union[*callables], and If we assert not callable(type) then type has type Union[*uncallables]

If unsound_partition is set, assume that anything that is not clearly callable is in fact not callable. Otherwise we generate a new subtype that is callable.

Guaranteed to not return [], [].

Parameters
typ:TypeUndocumented
unsound​_partition:boolUndocumented
Returns
Tuple[List[Type], List[Type]]Undocumented
def propagate_up_typemap_info(self, existing_types, new_types): (source)

Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types.

Specifically, this function accepts two mappings of expression to original types: the original mapping (existing_types), and a new mapping (new_types) intended to update the original.

This function iterates through new_types and attempts to use the information to try refining any parent types that happen to be unions.

For example, suppose there are two types "A = Tuple[int, int]" and "B = Tuple[str, str]". Next, suppose that 'new_types' specifies the expression 'foo[0]' has a refined type of 'int' and that 'foo' was previously deduced to be of type Union[A, B].

Then, this function will observe that since A[0] is an int and B[0] is not, the type of 'foo' can be further refined from Union[A, B] into just B.

We perform this kind of "parent narrowing" for member lookup expressions and indexing expressions into tuples, namedtuples, and typeddicts. We repeat this narrowing recursively if the parent is also a "lookup expression". So for example, if we have the expression "foo['bar'].baz[0]", we'd potentially end up refining types for the expressions "foo", "foo['bar']", and "foo['bar'].baz".

We return the newly refined map. This map is guaranteed to be a superset of 'new_types'.

Parameters
existing​_types:Mapping[Expression, Type]Undocumented
new​_types:TypeMapUndocumented
Returns
TypeMapUndocumented
def push_type_map(self, type_map): (source)

Undocumented

Parameters
type​_map:TypeMapUndocumented
def refine_away_none_in_comparison(self, operands, operand_types, chain_indices, narrowable_operand_indices): (source)

Produces conditional type maps refining away None in an identity/equality chain.

For more details about what the different arguments mean, see the docstring of 'refine_identity_comparison_expression' up above.

Parameters
operands:List[Expression]Undocumented
operand​_types:List[Type]Undocumented
chain​_indices:List[int]Undocumented
narrowable​_operand​_indices:AbstractSet[int]Undocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def refine_identity_comparison_expression(self, operands, operand_types, chain_indices, narrowable_operand_indices, is_valid_target, coerce_only_in_literal_context): (source)

Produce conditional type maps refining expressions by an identity/equality comparison.

The 'operands' and 'operand_types' lists should be the full list of operands used in the overall comparison expression. The 'chain_indices' list is the list of indices actually used within this identity comparison chain.

So if we have the expression:

a <= b is c is d <= e

...then 'operands' and 'operand_types' would be lists of length 5 and 'chain_indices' would be the list [1, 2, 3].

The 'narrowable_operand_indices' parameter is the set of all indices we are allowed to refine the types of: that is, all operands that will potentially be a part of the output TypeMaps.

Although this function could theoretically try setting the types of the operands in the chains to the meet, doing that causes too many issues in real-world code. Instead, we use 'is_valid_target' to identify which of the given chain types we could plausibly use as the refined type for the expressions in the chain.

Similarly, 'coerce_only_in_literal_context' controls whether we should try coercing expressions in the chain to a Literal type. Performing this coercion is sometimes too aggressive of a narrowing, depending on context.

Parameters
operands:List[Expression]Undocumented
operand​_types:List[Type]Undocumented
chain​_indices:List[int]Undocumented
narrowable​_operand​_indices:AbstractSet[int]Undocumented
is​_valid​_target:Callable[[ProperType], bool]Undocumented
coerce​_only​_in​_literal​_context:boolUndocumented
Returns
Tuple[TypeMap, TypeMap]Undocumented
def refine_parent_types(self, existing_types, expr, expr_type): (source)

Checks if the given expr is a 'lookup operation' into a union and iteratively refines the parent types based on the 'expr_type'.

For example, if 'expr' is an expression like 'a.b.c.d', we'll potentially return refined types for expressions 'a', 'a.b', and 'a.b.c'.

For more details about what a 'lookup operation' is and how we use the expr_type to refine the parent types of lookup_expr, see the docstring in 'propagate_up_typemap_info'.

Parameters
existing​_types:Mapping[Expression, Type]Undocumented
expr:ExpressionUndocumented
expr​_type:TypeUndocumented
Returns
Mapping[Expression, Type]Undocumented
def reset(self): (source)

Cleanup stale state that might be left over from a typechecking run.

This allows us to reuse TypeChecker objects in fine-grained incremental mode.

def set_inference_error_fallback_type(self, var, lvalue, type): (source)

Store best known type for variable if type inference failed.

If a program ignores error on type inference error, the variable should get some inferred type so that if can used later on in the program. Example:

x = [] # type: ignore x.append(1) # Should be ok!

We implement this here by giving x a valid type (replacing inferred <nothing> with Any).

Parameters
var:VarUndocumented
lvalue:LvalueUndocumented
type:TypeUndocumented
def set_inferred_type(self, var, lvalue, type): (source)

Store inferred variable type.

Store the type to both the variable node and the expression node that refers to the variable (lvalue). If var is None, do nothing.

Parameters
var:VarUndocumented
lvalue:LvalueUndocumented
type:TypeUndocumented
def should_report_unreachable_issues(self): (source)

Undocumented

Returns
boolUndocumented
def should_suppress_optional_error(self, related_types): (source)

Undocumented

Parameters
related​_types:List[Type]Undocumented
Returns
boolUndocumented
def split_around_star(self, items, star_index, length): (source)

Splits a list of items in three to match another list of length 'length' that contains a starred expression at 'star_index' in the following way:

star_index = 2, length = 5 (i.e., [a,b,*,c,d]), items = [1,2,3,4,5,6,7] returns in: ([1,2], [3,4,5], [6,7])

Parameters
items:List[T]Undocumented
star​_index:intUndocumented
length:intUndocumented
Returns
Tuple[List[T], List[T], List[T]]Undocumented
def store_type(self, node, typ): (source)
Store the type of a node in the type map.
Parameters
node:ExpressionUndocumented
typ:TypeUndocumented
def str_type(self): (source)
Return instance type 'str'.
Returns
InstanceUndocumented
def temp_node(self, t, context=None): (source)
Create a temporary node with the given, fixed type.
Parameters
t:TypeUndocumented
context:Optional[Context]Undocumented
Returns
TempNodeUndocumented
def try_infer_partial_generic_type_from_assignment(self, lvalue, rvalue, op): (source)

Try to infer a precise type for partial generic type from assignment.

'op' is '=' for normal assignment and a binary operator ('+', ...) for augmented assignment.

Example where this happens:

x = [] if foo():

x = [1] # Infer List[int] as type of 'x'
Parameters
lvalue:LvalueUndocumented
rvalue:ExpressionUndocumented
op:strUndocumented
def try_infer_partial_type_from_indexed_assignment(self, lvalue, rvalue): (source)

Undocumented

Parameters
lvalue:IndexExprUndocumented
rvalue:ExpressionUndocumented
def type_check_raise(self, e, s, optional=False): (source)

Undocumented

Parameters
e:ExpressionUndocumented
s:RaiseStmtUndocumented
optional:boolUndocumented
def type_is_iterable(self, type): (source)

Undocumented

Parameters
type:TypeUndocumented
Returns
boolUndocumented
def type_type(self): (source)
Return instance type 'type'.
Returns
InstanceUndocumented
def visit_assert_stmt(self, s): (source)

Undocumented

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

Type check an assignment statement.

Handle all kinds of assignment statements (simple, indexed, multiple).

Parameters
s:AssignmentStmtUndocumented
def visit_block(self, b): (source)

Undocumented

Parameters
b:BlockUndocumented
def visit_break_stmt(self, s): (source)

Undocumented

Parameters
s:BreakStmtUndocumented
def visit_class_def(self, defn): (source)
Type check a class definition.
Parameters
defn:ClassDefUndocumented
def visit_continue_stmt(self, s): (source)

Undocumented

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

Undocumented

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

Undocumented

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

Undocumented

Parameters
s:ExpressionStmtUndocumented
def visit_for_stmt(self, s): (source)
Type check a for statement.
Parameters
s:ForStmtUndocumented
def visit_func_def(self, defn): (source)

Undocumented

Parameters
defn:FuncDefUndocumented
def visit_if_stmt(self, s): (source)
Type check an if statement.
Parameters
s:IfStmtUndocumented
def visit_import(self, s): (source)

Undocumented

Parameters
s:ImportUndocumented
def visit_import_all(self, node): (source)

Undocumented

Parameters
node:ImportAllUndocumented
def visit_import_from(self, node): (source)

Undocumented

Parameters
node:ImportFromUndocumented
def visit_operator_assignment_stmt(self, s): (source)
Type check an operator assignment statement, e.g. x += 1.
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)
Type check a raise statement.
Parameters
s:RaiseStmtUndocumented
def visit_return_stmt(self, s): (source)
Type check a return statement.
Parameters
s:ReturnStmtUndocumented
def visit_try_stmt(self, s): (source)
Type check a try statement.
Parameters
s:TryStmtUndocumented
def visit_try_without_finally(self, s, try_frame): (source)

Type check a try statement, ignoring the finally block.

On entry, the top frame should receive all flow that exits the try block abnormally (i.e., such that the else block does not execute), and its parent should receive all flow that exits the try block normally.

Parameters
s:TryStmtUndocumented
try​_frame:boolUndocumented
def visit_while_stmt(self, s): (source)
Type check a while statement.
Parameters
s:WhileStmtUndocumented
def visit_with_stmt(self, s): (source)

Undocumented

Parameters
s:WithStmtUndocumented
partial_type_augmented_ops: set = (source)

Undocumented

Value
set([('builtins.list', '+'), ('builtins.set', '|')])
binder = (source)

Undocumented

current_node_deferred = (source)

Undocumented

deferred_nodes: list = (source)

Undocumented

dynamic_funcs: list = (source)

Undocumented

errors = (source)

Undocumented

expr_checker = (source)

Undocumented

globals = (source)

Undocumented

inferred_attribute_types = (source)

Undocumented

is_stub = (source)

Undocumented

is_typeshed_stub = (source)

Undocumented

module_refs = (source)

Undocumented

modules = (source)

Undocumented

no_partial_types: bool = (source)

Undocumented

partial_reported = (source)

Undocumented

partial_types: list = (source)

Undocumented

pass_num: int = (source)

Undocumented

plugin = (source)

Undocumented

recurse_into_functions: bool = (source)

Undocumented

return_types: list = (source)

Undocumented

scope = (source)

Undocumented

suppress_none_errors = (source)

Undocumented

tree = (source)

Undocumented

tscope = (source)

Undocumented

type_map: dict = (source)

Undocumented

var_decl_frames: dict = (source)

Undocumented

@property
type_context: List[Optional[Type]] = (source)
Return the type context of the plugin
def _check_for_truthy_type(self, t, expr): (source)

Undocumented

Parameters
t:TypeUndocumented
expr:ExpressionUndocumented
def _is_truthy_type(self, t): (source)

Undocumented

Parameters
t:ProperTypeUndocumented
Returns
boolUndocumented
def _visit_func_def(self, defn): (source)
Type check a function definition.
Parameters
defn:FuncDefUndocumented
def _visit_overloaded_func_def(self, defn): (source)

Undocumented

Parameters
defn:OverloadedFuncDefUndocumented
_is_final_def = (source)

Undocumented