class TypeChecker(NodeVisitor[None], CheckerPluginInterface): (source)
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 |
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:Statement | Undocumented |
else_body:Optional[ | Undocumented |
exit_condition:Optional[ | Undocumented |
Parameters | |
expr:Expression | Undocumented |
Returns | |
Tuple[ | Undocumented |
Parameters | |
index:Expression | Undocumented |
item_type:Type | Undocumented |
infer_lvalue_type:bool | Undocumented |
context:Context | Undocumented |
Parameters | |
expr:Expression | Undocumented |
Returns | |
Tuple[ | Undocumented |
Bind self-type and map type variables for a method.
Parameters | |
sym:SymbolTableNode | Undocumented |
typ:FunctionLike | Undocumented |
sub_info:TypeInfo | Undocumented |
super_info:TypeInfo | Undocumented |
Returns | |
FunctionLike | Undocumented |
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:FuncItem | Undocumented |
Parameters | |
lvalue:Lvalue | Undocumented |
rvalue:Expression | Undocumented |
infer_lvalue_type:bool | Undocumented |
new_syntax:bool | Undocumented |
Undocumented
Parameters | |
lvalues:List[ | Undocumented |
rvalue:Expression | Undocumented |
context:Context | Undocumented |
infer_lvalue_type:bool | Undocumented |
Undocumented
Parameters | |
expr:Expression | Undocumented |
target:Optional[ | Undocumented |
infer_lvalue_type:bool | Undocumented |
Returns | |
Type | Undocumented |
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:str | Undocumented |
base1:TypeInfo | Undocumented |
base2:TypeInfo | Undocumented |
ctx:TypeInfo | Undocumented |
Undocumented
Parameters | |
lvalue:RefExpr | Undocumented |
lvalue_type:Optional[ | Undocumented |
rvalue:Expression | Undocumented |
Returns | |
bool | Undocumented |
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:Var | Undocumented |
base:TypeInfo | Undocumented |
base_node:Optional[ | Undocumented |
Returns | |
bool | Undocumented |
Parameters | |
n:Expression | Undocumented |
Returns | |
Type | Undocumented |
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[ | Undocumented |
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().
Undocumented
Parameters | |
func:FuncDef | Undocumented |
dec_type:Type | Undocumented |
dec_expr:Expression | Undocumented |
Parameters | |
defn:FuncItem | Undocumented |
typ:CallableType | Undocumented |
name:Optional[ | Undocumented |
Type check a function.
If type_override is provided, use it as the function type.
Parameters | |
defn:FuncItem | Undocumented |
type_override:Optional[ | Undocumented |
name:Optional[ | Undocumented |
Type check indexed assignment base[index] = rvalue.
The lvalue argument is the base[index] expression.
Parameters | |
lvalue:IndexExpr | Undocumented |
rvalue:Expression | Undocumented |
context:Context | Undocumented |
Check that keywords in a class definition are valid arguments for __init_subclass__().
Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here. Child.__init_subclass__ is never called.
Parameters | |
defn:ClassDef | Undocumented |
Check an inplace operator method such as __iadd__.
They cannot arbitrarily overlap with __add__.
Parameters | |
defn:FuncBase | Undocumented |
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:Type | Undocumented |
attribute_type:Type | Undocumented |
rvalue:Expression | Undocumented |
context:Context | Undocumented |
Returns | |
Tuple[ | Undocumented |
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[ | Undocumented |
base:TypeInfo | Undocumented |
Returns | |
bool | Undocumented |
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[ | Undocumented |
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[ | Undocumented |
name:str | Undocumented |
base:TypeInfo | Undocumented |
Returns | |
bool | Undocumented |
Parameters | |
lvalues:List[ | Undocumented |
rvalue:Expression | Undocumented |
context:Context | Undocumented |
infer_lvalue_type:bool | Undocumented |
rv_type:Optional[ | Undocumented |
undefined_rvalue:bool | Undocumented |
Undocumented
Parameters | |
lvalues:List[ | Undocumented |
rvalue:Expression | Undocumented |
rvalue_type:TupleType | Undocumented |
context:Context | Undocumented |
undefined_rvalue:bool | Undocumented |
infer_lvalue_type:bool | Undocumented |
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[ | Undocumented |
rvalue:Expression | Undocumented |
rvalue_type:UnionType | Undocumented |
context:Context | Undocumented |
infer_lvalue_type:bool | Undocumented |
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:CallableType | Undocumented |
reverse_name:str | Undocumented |
reverse_class:TypeInfo | Undocumented |
forward_type:Type | Undocumented |
forward_name:str | Undocumented |
forward_base:Type | Undocumented |
context:Context | Undocumented |
Check a method override with given signatures.
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:FunctionLike | Undocumented |
original:FunctionLike | Undocumented |
name:str | Undocumented |
name_in_super:str | Undocumented |
supertype:str | Undocumented |
original_class_or_static:bool | Undocumented |
override_class_or_static:bool | Undocumented |
node:Context | Undocumented |
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:ClassDef | Undocumented |
Parameters | |
defn:FuncItem | Undocumented |
reverse_type:CallableType | Undocumented |
reverse_name:str | Undocumented |
context:Context | Undocumented |
Undocumented
Parameters | |
lvalues:List[ | Undocumented |
rvalue_count:int | Undocumented |
context:Context | Undocumented |
Returns | |
bool | Undocumented |
Run second or following pass of type checking.
This goes through deferred nodes, returning True if there were any.
Parameters | |
todo:Optional[ | Undocumented |
Returns | |
bool | Undocumented |
Undocumented
Parameters | |
lvalue_type:Optional[ | Undocumented |
rvalue:Expression | Undocumented |
context:Context | Undocumented |
msg:str | Undocumented |
lvalue_name:str | Undocumented |
rvalue_name:str | Undocumented |
code:Optional[ | Undocumented |
Returns | |
Type | Undocumented |
Parameters | |
subtype:Type | Undocumented |
supertype:Type | Undocumented |
context:Context | Undocumented |
msg:Union[ | Undocumented |
subtype_label:Optional[ | Undocumented |
supertype_label:Optional[ | Undocumented |
code:Optional[ | Undocumented |
outer_context:Optional[ | Undocumented |
Returns | |
bool | Undocumented |
Parameters | |
node:MypyFile | Undocumented |
Undocumented
Parameters | |
expr:Expression | Undocumented |
target:Optional[ | Undocumented |
infer_lvalue_type:bool | Undocumented |
Returns | |
Type | Undocumented |
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:Expression | Undocumented |
current_type:Optional[ | Undocumented |
Returns | |
Tuple[ | Undocumented |
Undocumented
Parameters | |
expr:Expression | Undocumented |
expr_type:Type | Undocumented |
type_ranges:Optional[ | Undocumented |
Returns | |
Tuple[ | Undocumented |
Defer a node for processing during next type-checking pass.
NOTE: this can't handle nested functions/methods.
Parameters | |
node:DeferredNodeType | Undocumented |
enclosing_class:Optional[ | Undocumented |
Parameters | |
is_final_def:bool | Undocumented |
Returns | |
Iterator[ | Undocumented |
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:bool | Undocumented |
is_class:bool | Undocumented |
Returns | |
Iterator[ | Undocumented |
Undocumented
Parameters | |
defn:FuncItem | Undocumented |
typ:CallableType | Undocumented |
Returns | |
List[ | Undocumented |
mypy.plugin.CheckerPluginInterface.fail
Parameters | |
msg:Union[ | Undocumented |
context:Context | Undocumented |
code:Optional[ | Undocumented |
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:Expression | Undocumented |
Returns | |
Tuple[ | Undocumented |
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:Var | Undocumented |
Returns | |
Optional[ | Undocumented |
Narrow types based on any checks of the type type(x) == T
node: The node that might contain the comparison expr_indices: The list of indices of expressions in node that are being
compared
Parameters | |
node:ComparisonExpr | Undocumented |
expr_indices:List[ | Undocumented |
Returns | |
Tuple[ | Undocumented |
Parameters | |
typ:Type | Undocumented |
n:Expression | Undocumented |
Returns | |
List[ | Undocumented |
Handle a reference to a partial type through a var.
(Used by checkexpr and checkmember.)
Parameters | |
typ:PartialType | Undocumented |
is_lvalue:bool | Undocumented |
node:Var | Undocumented |
context:Context | Undocumented |
Returns | |
Type | Undocumented |
Should we type-check the current function?
Returns | |
bool | Undocumented |
Parameters | |
node:CallExpr | Undocumented |
expr:Expression | Undocumented |
type_map:Dict[ | Undocumented |
Returns | |
Tuple[ | Undocumented |
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:Instance | Undocumented |
callable_type:CallableType | Undocumented |
Returns | |
Instance | Undocumented |
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[ | Undocumented |
ctx:Context | Undocumented |
Returns | |
Optional[ | Undocumented |
Undocumented
Parameters | |
lvalue:Lvalue | Undocumented |
typ:Optional[ | Undocumented |
Returns | |
bool | Undocumented |
Is typ
a valid type for an async generator?
True if typ
is a supertype of AsyncGenerator.
Parameters | |
typ:Type | Undocumented |
Returns | |
bool | Undocumented |
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:Type | Undocumented |
is_coroutine:bool | Undocumented |
Returns | |
bool | Undocumented |
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:Statement | Undocumented |
Returns | |
bool | Undocumented |
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:Block | Undocumented |
Returns | |
bool | Undocumented |
Undocumented
Parameters | |
forward_item:CallableType | Undocumented |
forward_base:Type | Undocumented |
reverse_type:CallableType | Undocumented |
Returns | |
bool | Undocumented |
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:ProperType | Undocumented |
Returns | |
bool | Undocumented |
Parameters | |
name:str | Undocumented |
Returns | |
SymbolTableNode | Undocumented |
Return an instance type with given name and implicit Any type args.
For example, named_type('builtins.object') produces the 'object' type.
Parameters | |
name:str | Undocumented |
Returns | |
Instance | Undocumented |
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:Type | Undocumented |
unsound_partition:bool | Undocumented |
Returns | |
Tuple[ | Undocumented |
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[ | Undocumented |
new_types:TypeMap | Undocumented |
Returns | |
TypeMap | Undocumented |
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[ | Undocumented |
operand_types:List[ | Undocumented |
chain_indices:List[ | Undocumented |
narrowable_operand_indices:AbstractSet[ | Undocumented |
Returns | |
Tuple[ | Undocumented |
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[ | Undocumented |
operand_types:List[ | Undocumented |
chain_indices:List[ | Undocumented |
narrowable_operand_indices:AbstractSet[ | Undocumented |
is_valid_target:Callable[ | Undocumented |
coerce_only_in_literal_context:bool | Undocumented |
Returns | |
Tuple[ | Undocumented |
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[ | Undocumented |
expr:Expression | Undocumented |
expr_type:Type | Undocumented |
Returns | |
Mapping[ | Undocumented |
Cleanup stale state that might be left over from a typechecking run.
This allows us to reuse TypeChecker objects in fine-grained incremental mode.
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:Var | Undocumented |
lvalue:Lvalue | Undocumented |
type:Type | Undocumented |
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[ | Undocumented |
star_index:int | Undocumented |
length:int | Undocumented |
Returns | |
Tuple[ | Undocumented |
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:Lvalue | Undocumented |
rvalue:Expression | Undocumented |
op:str | Undocumented |
Type check an assignment statement.
Handle all kinds of assignment statements (simple, indexed, multiple).
Parameters | |
s:AssignmentStmt | Undocumented |
Parameters | |
s:OperatorAssignmentStmt | Undocumented |
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:TryStmt | Undocumented |
try_frame:bool | Undocumented |