class TypeChecker(NodeVisitor[
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 |
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 | add |
Inject an extra attribute with Any type using fallbacks. |
Method | analyze |
Analyse async iterable expression and return iterator and iterator item types. |
Method | analyze |
Check if a type is a nominal container of a union of such. |
Method | analyze |
Type check or infer for loop or list comprehension index vars. |
Method | analyze |
Analyse iterable expression and return iterator and iterator item types. |
Method | analyze |
Analyse iterable type and return iterator and iterator item types. |
Method | analyze |
Try to infer native int item type from arguments to range(...). |
Method | bind |
Bind self-type and map type variables for a method. |
Method | check |
Undocumented |
Method | check |
Generate error if the return type of __exit__ is problematic. |
Method | check |
Type check a single assignment: lvalue = rvalue. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Check if attribute name in base1 is compatible with base2 in multiple inheritance. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Check if an assignment overrides a final attribute in a base class. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Non-enum mixins cannot appear after enum bases; this is disallowed at runtime: |
Method | check |
Undocumented |
Method | check |
Type check an exception handler test clause. |
Method | check |
Check if this assignment does not assign to a final attribute. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Type check the entire file, but defer functions with unresolved references. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Type check a function definition. |
Method | check |
Type check a function. |
Method | check |
Undocumented |
Method | check |
Check that a final variable doesn't override writeable attribute. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Type check indexed assignment base[index] = rvalue. |
Method | check |
Check that keywords in a class definition are valid arguments for __init_subclass__(). |
Method | check |
Check an inplace operator method such as __iadd__. |
Method | check |
Undocumented |
Method | check |
Check that __match_args__ contains literal strings |
Method | check |
Type member assignment. |
Method | check |
Ensures that metaclasses of all parent types are compatible. |
Method | check |
Check if method definition is compatible with a base class. |
Method | check |
Check if function definition is compatible with base classes. |
Method | check |
Check if overriding an attribute `name` of `base` with `defn` is valid. |
Method | check |
Check the assignment of one rvalue to a number of lvalues. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Check assignment to multiple lvalue targets when rvalue type is a Union[...]. For example: |
Method | check |
Check for multiple inheritance related errors. |
Method | check |
Check for overlapping method and reverse method signatures. |
Method | check |
Undocumented |
Method | check |
Check a method override with given signatures. |
Method | check |
Undocumented |
Method | check |
Check if the given type becomes a subtype when awaited. |
Method | check |
Check that protocol definition is compatible with declared variances of type variables. |
Method | check |
Undocumented |
Method | check |
Check a reverse operator method such as __radd__. |
Method | check |
Undocumented |
Method | check |
Run second or following pass of type checking. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | check |
Check the type of __slots__. |
Method | check |
Generate an error if the subtype is not compatible with supertype. |
Method | check |
Check only the top-level of a module, skipping function definitions. |
Method | check |
Undocumented |
Method | check |
Fails when the return typevar is not defined in arguments. |
Method | check |
Undocumented |
Method | check |
Undocumented |
Method | checking |
Undocumented |
Method | conditional |
Takes in an expression and the current type of the expression. |
Method | conditional |
Narrows the type of `iterable_type` based on the type of `item_type`. For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s). |
Method | conditional |
Undocumented |
Method | contains |
Undocumented |
Method | default |
Exception type to return in case of a previous type error. |
Method | defer |
Defer a node for processing during next type-checking pass. |
Method | determine |
Undocumented |
Method | enter |
Undocumented |
Method | enter |
Store whether the current checked assignment is a final declaration. |
Method | enter |
Enter a new scope for collecting partial types. |
Method | expand |
Undocumented |
Method | fail |
Produce an error message. |
Method | find |
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 |
Undocumented |
Method | find |
Look for an active partial type scope containing variable. |
Method | find |
Look for partial type scope containing variable. |
Method | find |
Narrow types based on any checks of the type ``type(x) == T`` |
Method | flatten |
Undocumented |
Method | function |
Undocumented |
Method | get |
Undocumented |
Method | get |
Check whether we a currently checking a final declaration. |
Method | get |
Given a declared generator return type (t), return the type its yield receives (tc). |
Method | get |
Given the declared return type of a generator (t), return the type it returns (tr). |
Method | get |
Given the declared return type of a generator (t), return the type it yields (ty). |
Method | get |
Undocumented |
Method | get |
Undocumented |
Method | get |
If type implements Awaitable[X] with non-Any X, return X. |
Method | get |
Helper for check_except_handler_test to retrieve handler types. |
Method | get |
Undocumented |
Method | handle |
Undocumented |
Method | handle |
Handle a reference to a partial type through a var. |
Method | has |
Undocumented |
Method | has |
Undocumented |
Method | hasattr |
Simple support for hasattr() checks. |
Method | in |
Should we type-check the current function? |
Method | infer |
Infer type restrictions for an expression in issubclass call. |
Method | infer |
Undocumented |
Method | infer |
Infer the type of initialized variables from initializer type. |
Method | infer |
Undocumented |
Method | inference |
Undocumented |
Method | intersect |
Creates a fake type that represents the intersection of an Instance and a CallableType. |
Method | intersect |
Try creating an ad-hoc intersection of the given instances. |
Method | is |
Undocumented |
Method | is |
Is `typ` a valid type for an async generator? |
Method | is |
Undocumented |
Method | is |
Undocumented |
Method | is |
Undocumented |
Method | is |
Undocumented |
Method | is |
Is `typ` a valid type for a generator/coroutine? |
Method | is |
Returns true if this expression (with the given type context) is an Enum literal. |
Method | is |
Returns 'true' if the given statement either throws an error of some kind or is a no-op. |
Method | is |
Undocumented |
Method | is |
Undocumented |
Method | is |
Check if t can be used as the basis for a partial defaultdict value type. |
Method | is |
Check if an attribute is writable |
Method | iterable |
Undocumented |
Method | local |
Store inferred types into a temporary type map (returned). |
Method | lookup |
Look up a definition from the symbol table with the given name. |
Method | lookup |
Undocumented |
Method | lookup |
Undocumented |
Method | lookup |
Undocumented |
Method | lookup |
Undocumented |
Method | lvalue |
Undocumented |
Method | lvalue |
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 |
Produce a new type that makes type Callable with a generic callable type. |
Method | make |
Undocumented |
Method | named |
Return an instance with the given name and type arguments. |
Method | named |
Return an instance type with given name and implicit Any type args. |
Method | note |
Produce a note. |
Method | partition |
Partitions a type into callable subtypes and uncallable subtypes. |
Method | partition |
Undocumented |
Method | propagate |
Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types. |
Method | push |
Undocumented |
Method | refine |
Produces conditional type maps refining away None in an identity/equality chain. |
Method | refine |
Produce conditional type maps refining expressions by an identity/equality comparison. |
Method | refine |
Checks if the given expr is a 'lookup operation' into a union and iteratively refines the parent types based on the 'expr_type'. |
Method | remove |
Undocumented |
Method | reset |
Cleanup stale state that might be left over from a typechecking run. |
Method | set |
Store best known type for variable if type inference failed. |
Method | set |
Store inferred variable type. |
Method | should |
Undocumented |
Method | simple |
Returns True for expressions for which inferred type should not depend on context. |
Method | split |
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 |
Store the type of a node in the type map. |
Method | store |
Undocumented |
Method | str |
Return instance type 'str'. |
Method | temp |
Create a temporary node with the given, fixed type. |
Method | try |
Try to infer a precise type for partial generic type from assignment. |
Method | try |
Undocumented |
Method | type |
Undocumented |
Method | type |
Undocumented |
Method | type |
Some types require usage in all cases. The classic example is an unused coroutine. |
Method | type |
Return instance type 'type'. |
Method | visit |
Undocumented |
Method | visit |
Type check an assignment statement. |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Type check a class definition. |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Type check a for statement. |
Method | visit |
Undocumented |
Method | visit |
Type check an if statement. |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Type check an operator assignment statement, e.g. x += 1. |
Method | visit |
Undocumented |
Method | visit |
Type check a raise statement. |
Method | visit |
Type check a return statement. |
Method | visit |
Type check a try statement. |
Method | visit |
Type check a try statement, ignoring the finally block. |
Method | visit |
Type check a while statement. |
Method | visit |
Undocumented |
Method | wrap |
Transform except* variable type into an appropriate exception group. |
Constant | partial |
Undocumented |
Instance Variable | allow |
Undocumented |
Instance Variable | binder |
Undocumented |
Instance Variable | checking |
Undocumented |
Instance Variable | current |
Undocumented |
Instance Variable | deferred |
Undocumented |
Instance Variable | dynamic |
Undocumented |
Instance Variable | errors |
Undocumented |
Instance Variable | expr |
Undocumented |
Instance Variable | globals |
Undocumented |
Instance Variable | inferred |
Undocumented |
Instance Variable | is |
Undocumented |
Instance Variable | is |
Undocumented |
Instance Variable | module |
Undocumented |
Instance Variable | modules |
Undocumented |
Instance Variable | msg |
Undocumented |
Instance Variable | no |
Undocumented |
Instance Variable | options |
Undocumented |
Instance Variable | partial |
Undocumented |
Instance Variable | partial |
Undocumented |
Instance Variable | pass |
Undocumented |
Instance Variable | path |
Undocumented |
Instance Variable | pattern |
Undocumented |
Instance Variable | plugin |
Undocumented |
Instance Variable | recurse |
Undocumented |
Instance Variable | return |
Undocumented |
Instance Variable | scope |
Undocumented |
Instance Variable | temp |
Undocumented |
Instance Variable | tree |
Undocumented |
Instance Variable | tscope |
Undocumented |
Instance Variable | var |
Undocumented |
Property | type |
Return the type context of the plugin |
Method | _check |
Undocumented |
Method | _is |
Undocumented |
Method | _visit |
Type check a function definition. |
Method | _visit |
Undocumented |
Instance Variable | _is |
Undocumented |
Instance Variable | _type |
Undocumented |
Inherited from NodeVisitor
:
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Method | visit |
Undocumented |
Errors
, modules: dict[ str, MypyFile]
, options: Options
, tree: MypyFile
, path: str
, plugin: Plugin
, per_line_checking_time_ns: dict[ int, int]
):
(source)
¶
Construct a type checker. Use errors to report type check errors.
Statement
, else_body: Statement|None
= None, *, exit_condition: Expression|None
= 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.
Check if a type is a nominal container of a union of such. Return the corresponding container item type.
Expression
, item_type: Type
, infer_lvalue_type: bool
, context: Context
):
(source)
¶
Type check or infer for loop or list comprehension index vars.
Type
, context: Context
) -> tuple[ Type, Type]
:
(source)
¶
Analyse iterable type and return iterator and iterator item types.
Try to infer native int item type from arguments to range(...). For example, return i64 if the expression is "range(0, i64(n))". Return None if unsuccessful.
SymbolTableNode
, typ: FunctionLike
, sub_info: TypeInfo
, super_info: TypeInfo
) -> FunctionLike
:
(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
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.
Lvalue
, rvalue: Expression
, infer_lvalue_type: bool
= True, new_syntax: bool
= False):
(source)
¶
Type check a single assignment: lvalue = rvalue.
list[ Lvalue]
, rvalue: Expression
, context: Context
, infer_lvalue_type: bool
= True):
(source)
¶
Undocumented
Expression
, target: Expression|None
, infer_lvalue_type: bool
) -> Type
:
(source)
¶
Undocumented
str
, base1: TypeInfo
, base2: TypeInfo
, ctx: TypeInfo
):
(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
RefExpr
, lvalue_type: Type|None
, rvalue: Expression
) -> bool
:
(source)
¶
Undocumented
Var
, base: TypeInfo
, base_node: Node|None
) -> bool
:
(source)
¶
Undocumented
Var
, base: TypeInfo
, base_node: Node|None
) -> bool
:
(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()`.
RefExpr
, lvalue_type: Type|None
, rvalue: Expression
, base: TypeInfo
, base_type: Type
, base_node: Node
) -> bool
:
(source)
¶
Undocumented
Non-enum mixins cannot appear after enum bases; this is disallowed at runtime: class Foo: ... class Bar(enum.Enum, Foo): ... But any number of enum mixins can appear in a class definition (even if multiple enum bases define __new__). So this is fine: class Foo(enum.Enum): def __new__(cls, val): ... class Bar(enum.Enum): def __new__(cls, val): ... class Baz(int, Foo, Bar, enum.Flag): ...
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.
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().
FuncDef
, dec_type: Type
, dec_expr: Expression
):
(source)
¶
Undocumented
FuncItem
, typ: CallableType
, name: str|None
, allow_empty: bool
= False):
(source)
¶
Type check a function definition.
FuncItem
, type_override: CallableType|None
= None, name: str|None
= None, allow_empty: bool
= False):
(source)
¶
Type check a function. If type_override is provided, use it as the function type.
str
, base_node: Node|None
, ctx: Context
):
(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!
IndexExpr
, rvalue: Expression
, context: Context
):
(source)
¶
Type check indexed assignment base[index] = rvalue. The lvalue argument is the base[index] expression.
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.
Type
, attribute_type: Type
, rvalue: Expression
, context: Context
) -> tuple[ Type, Type, bool]
:
(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__().
(FuncDef|OverloadedFuncDef)|Decorator
, base: TypeInfo
) -> bool
:
(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.
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.
(FuncDef|OverloadedFuncDef)|Decorator
, name: str
, base: TypeInfo
) -> bool
:
(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.
list[ Lvalue]
, rvalue: Expression
, context: Context
, infer_lvalue_type: bool
= True, rv_type: Type|None
= None, undefined_rvalue: bool
= False):
(source)
¶
Check the assignment of one rvalue to a number of lvalues.
list[ Lvalue]
, rvalue_type: Type
, context: Context
, infer_lvalue_type: bool
= True):
(source)
¶
Undocumented
list[ Lvalue]
, rvalue: Expression
, rvalue_type: TupleType
, context: Context
, undefined_rvalue: bool
, infer_lvalue_type: bool
= True):
(source)
¶
Undocumented
list[ Expression]
, rvalue: Expression
, rvalue_type: UnionType
, context: Context
, infer_lvalue_type: bool
):
(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.
CallableType
, reverse_name: str
, reverse_class: TypeInfo
, forward_type: Type
, forward_name: str
, forward_base: Type
, context: 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__(...)`.
FunctionLike
, original: FunctionLike
, name: str
, name_in_super: str
, supertype: str
, original_class_or_static: bool
, override_class_or_static: bool
, node: Context
):
(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.
Type
, supertype: Type
, context: Context
):
(source)
¶
Check if the given type becomes a subtype when awaited.
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.
FuncItem
, reverse_type: CallableType
, reverse_name: str
, context: Context
):
(source)
¶
Check a reverse operator method such as __radd__.
list[ Lvalue]
, rvalue_count: int
, context: Context
) -> bool
:
(source)
¶
Undocumented
Sequence[ DeferredNode|FineGrainedDeferredNode]|None
= None) -> bool
:
(source)
¶
Run second or following pass of type checking. This goes through deferred nodes, returning True if there were any.
Type|None
, rvalue: Expression
, context: Context
, msg: ErrorMessage
= message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, lvalue_name: str
= 'variable', rvalue_name: str
= 'expression', *, notes: list[ str]|None
= None) -> Type
:
(source)
¶
Undocumented
Type
, supertype: Type
, context: Context
, msg: str
, subtype_label: str|None
= None, supertype_label: str|None
= None, *, notes: list[ str]|None
= None, code: ErrorCode|None
= None, outer_context: Context|None
= None) -> bool
:Type
, supertype: Type
, context: Context
, msg: ErrorMessage
, subtype_label: str|None
= None, supertype_label: str|None
= None, *, notes: list[ str]|None
= None, outer_context: Context|None
= None) -> bool
:Generate an error if the subtype is not compatible with supertype.
Expression
, target: Expression|None
, infer_lvalue_type: bool
) -> Type
:
(source)
¶
Undocumented
Expression
, current_type: Type|None
) -> tuple[ TypeMap, TypeMap]
:
(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.
Type
, iterable_type: Type
) -> tuple[ Type|None, Type|None]
:
(source)
¶
Narrows the type of `iterable_type` based on the type of `item_type`. For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s).
Type
, type_ranges: list[ TypeRange]|None
, ctx: Context
, default: None
= None) -> tuple[ Type|None, Type|None]
:Type
, type_ranges: list[ TypeRange]|None
, ctx: Context
, default: Type
) -> tuple[ Type, Type]
:Undocumented
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.
def enter_partial_types(self, *, is_function:
bool
= False, is_class: bool
= False) -> Iterator[ None]
:
(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.
FuncItem
, typ: CallableType
) -> list[ tuple[ FuncItem, CallableType]]
:
(source)
¶
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.
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.
Var
) -> tuple[ bool, bool, dict[ Var, Context]|None]
:
(source)
¶
Look for partial type scope containing variable. Return tuple (is the scope active, is the scope a local scope, scope).
ComparisonExpr
, expr_indices: list[ int]
) -> tuple[ TypeMap, TypeMap]
:
(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
Type
, local_errors: ErrorWatcher
) -> Type|None
:
(source)
¶
If type implements Awaitable[X] with non-Any X, return X. In all other cases return None. This method must be called in context of local_errors.
PartialType
, is_lvalue: bool
, node: Var
, context: Context
) -> Type
:
(source)
¶
Handle a reference to a partial type through a var. (Used by checkexpr and checkmember.)
Expression
, source_type: Type
, name: str
) -> tuple[ TypeMap, TypeMap]
:
(source)
¶
Simple support for hasattr() checks. Essentially the logic is following: * In the if branch, keep types that already has a valid attribute as is, for other inject an attribute with `Any` type. * In the else branch, remove types that already have a valid attribute, while keeping the rest.
Should we type-check the current function? - Yes if --check-untyped-defs is set. - Yes outside functions. - Yes in annotated functions. - No otherwise.
CallExpr
, expr: Expression
) -> tuple[ TypeMap, TypeMap]
:
(source)
¶
Infer type restrictions for an expression in issubclass call.
Var
, lvalue: Lvalue
, init_type: Type
, context: Context
):
(source)
¶
Infer the type of initialized variables from initializer type.
list[ TypeMap]
) -> dict[ Var, Type]
:
(source)
¶
Undocumented
Instance
, callable_type: CallableType
) -> Instance
:
(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.
tuple[ Instance, Instance]
, errors: list[ tuple[ str, str]]
) -> Instance|None
:
(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.
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).
Returns true if this expression (with the given type context) is an Enum literal. For example, if we had an enum: class Foo(Enum): A = 1 B = 2 ...and if the expression 'Foo' referred to that enum within the current type context, then the expression 'Foo.A' would be a literal enum. However, if we did 'a = Foo.A', then the variable 'a' would *not* be a literal enum. We occasionally special-case expressions like 'Foo.A' and treat them as a single primitive unit for the same reasons we sometimes treat 'True', 'False', or 'None' as a single primitive unit.
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.
CallableType
, forward_base: Type
, reverse_type: CallableType
) -> bool
:
(source)
¶
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)
Store inferred types into a temporary type map (returned). This can be used to perform type checking "experiments" without affecting exported types (which are used by mypyc).
list[ Lvalue]
, rvalue_type: TupleType
) -> Type
:
(source)
¶
Undocumented
Var
, base: TypeInfo
) -> tuple[ Type|None, Node|None]
:
(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.
str
, class_gen_name: str
, class_short_name: str
, bases: list[ Instance]
) -> tuple[ ClassDef, TypeInfo]
:
(source)
¶
Undocumented
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.
Return an instance type with given name and implicit Any type args. For example, named_type('builtins.object') produces the 'object' type.
str|ErrorMessage
, context: Context
, offset: int
= 0, *, code: ErrorCode|None
= None):
(source)
¶
Produce a note.
Type
, unsound_partition: bool
) -> tuple[ list[ Type], list[ Type]]
:
(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 [], [].
UnionType
, name: str
) -> tuple[ list[ Type], list[ Type]]
:
(source)
¶
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'.
list[ Expression]
, operand_types: list[ Type]
, chain_indices: list[ int]
, narrowable_operand_indices: AbstractSet[ int]
) -> tuple[ TypeMap, TypeMap]
:
(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.
list[ Expression]
, operand_types: list[ Type]
, chain_indices: list[ int]
, narrowable_operand_indices: AbstractSet[ int]
, is_valid_target: Callable[ [ ProperType], bool]
, coerce_only_in_literal_context: bool
) -> tuple[ TypeMap, TypeMap]
:
(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.
Expression
, expr_type: Type
) -> Mapping[ Expression, 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'.
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).
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.
Returns True for expressions for which inferred type should not depend on context. Note that this function can still return False for some expressions where inferred type does not depend on context. It only exists for performance optimizations.
list[ T]
, star_index: int
, length: int
) -> tuple[ list[ T], list[ T], list[ T]]
:
(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])
Lvalue
, rvalue: Expression
, op: str
):
(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'
IndexExpr
, rvalue: Expression
):
(source)
¶
Undocumented
Some types require usage in all cases. The classic example is an unused coroutine. In the case that it does require usage, returns a note to attach to the error message.
Type check an assignment statement. Handle all kinds of assignment statements (simple, indexed, multiple).
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.