class documentation

class ExpressionChecker(ExpressionVisitor[Type]): (source)

View In Hierarchy

Expression type checker. This class works closely together with checker.TypeChecker.

Method __init__ Construct an expression type checker.
Method accept Type check a node in the given type context. If allow_none_return is True and this expression is a call, allow it to return None. This applies only to this expression and not any subexpressions.
Method alias_type_in_runtime_context Get type of a type alias (could be generic) in a runtime expression.
Method always_returns_none Check if `node` refers to something explicitly annotated as only returning None.
Method analyze_cond_branch Undocumented
Method analyze_external_member_access Analyse member access that is external, i.e. it cannot refer to private definitions. Return the result type.
Method analyze_ordinary_member_access Analyse member expression or member lvalue.
Method analyze_ref_expr Undocumented
Method analyze_type_type_callee Analyze the callee X in X(...) where X is Type[item].
Method analyze_var_ref Undocumented
Method apply_function_plugin Use special case logic to infer the return type of a specific named function/method.
Method apply_function_signature_hook Apply a plugin hook that may infer a more precise signature for a function.
Method apply_generic_arguments Simple wrapper around mypy.applytype.apply_generic_arguments.
Method apply_inferred_arguments Apply inferred values of type arguments to a generic function.
Method apply_method_signature_hook Apply a plugin hook that may infer a more precise signature for a method.
Method apply_signature_hook Helper to apply a signature hook for either a function or method
Method apply_type_arguments_to_callable Apply type arguments to a generic callable type coming from a type object.
Method argument_infer_context Undocumented
Method bool_type Return instance type 'bool'.
Method can_return_none Is the given attribute a method with a None-compatible return type?
Method check_any_type_call Undocumented
Method check_arg Check the type of a single argument in a call.
Method check_argument_count Check that there is a value for all required arguments to a function.
Method check_argument_types Check argument types against a callable type.
Method check_awaitable_expr Check the argument to `await` and extract the type of value.
Method check_boolean_op Type check a boolean operation ('and' or 'or').
Method check_call Type check a call.
Method check_call_expr_with_callee_type Type check call expression.
Method check_callable_call Type check a call that targets a callable value.
Method check_for_comp Check the for_comp part of comprehensions. That is the part from 'for': ... for x in y if z
Method check_for_extra_actual_arguments Check for extra actual arguments.
Method check_generator_or_comprehension Type check a generator expression or a list comprehension.
Method check_list_multiply Type check an expression of form '[...] * e'.
Method check_lst_expr Undocumented
Method check_method_call Type check a call to a method with the given name and type on an object.
Method check_method_call_by_name Type check a call to a named method on an object.
Method check_op Type check a binary operation which maps to a method call.
Method check_op_reversible Undocumented
Method check_overload_call Checks a call to an overloaded function.
Method check_protocol_issubclass Undocumented
Method check_runtime_protocol_test Undocumented
Method check_str_format_call More precise type checking for str.format() calls on literals.
Method check_typeddict_call Undocumented
Method check_typeddict_call_with_dict Undocumented
Method check_typeddict_call_with_kwargs Undocumented
Method check_typeddict_literal_in_context Undocumented
Method check_union_call Undocumented
Method check_union_call_expr Type check calling a member expression where the base type is a union.
Method check_union_method_call_by_name Type check a call to a named method on an object with union type.
Method combine_function_signatures Accepts a list of function signatures and attempts to combine them together into a new CallableType consisting of the union of all of the given arguments and return types.
Method concat_tuples Concatenate two fixed length tuples.
Method dangerous_comparison Check for dangerous non-overlapping comparisons like 42 == 'no'.
Method defn_returns_none Check if `defn` can _only_ return None.
Method erased_signature_similarity Determine whether arguments could match the signature at runtime, after erasing types.
Method fast_container_type Fast path to determine the type of a list or set literal, based on the list of entries. This mostly impacts large module-level constant definitions.
Method fast_dict_type Fast path to determine the type of a dict literal, based on the list of entries. This mostly impacts large module-level constant definitions.
Method find_partial_type_ref_fast_path If expression has a partial generic type, return it without additional checks.
Method find_typeddict_context Undocumented
Method get_arg_infer_passes Return pass numbers for args for two-pass argument type inference.
Method get_partial_self_var Get variable node for a partial self attribute.
Method get_partial_var Undocumented
Method has_member Does type have member with the given name?
Method infer_arg_types_in_context Infer argument expression types using a callable type as context.
Method infer_arg_types_in_empty_context Infer argument expression types in an empty context.
Method infer_function_type_arguments Infer the type arguments for a generic callee type.
Method infer_function_type_arguments_pass2 Perform second pass of generic function type argument inference.
Method infer_function_type_arguments_using_context Unify callable return type to type context to infer type vars.
Method infer_lambda_type_using_context Try to infer lambda expression type using context.
Method infer_literal_expr_type Analyzes the given literal expression and determines if we should be inferring an Instance type, a Literal[...] type, or an Instance that remembers the original literal. We...
Method infer_more_unions_for_recursive_type Adjust type inference of unions if type context has a recursive type.
Method infer_overload_return_type Attempts to find the first matching callable from the given list.
Method is_literal_context Undocumented
Method is_valid_keyword_var_arg Is a type valid as a **kwargs argument?
Method is_valid_var_arg Is a type valid as a *args argument?
Method match_typeddict_call_with_dict Undocumented
Method method_fullname Convert a method name to a fully qualified name, based on the type of the object that it is invoked on. Return `None` if the name of `object_type` cannot be determined.
Method missing_classvar_callable_note Undocumented
Method module_type Undocumented
Method named_type Return an instance type with type given by the name and no type arguments. Alias for TypeChecker.named_type.
Method narrow_type_from_binder Narrow down a known type of expression using information in conditional type binder.
Method nonliteral_tuple_index_helper Undocumented
Method not_ready_callback Called when we can't infer the type of a variable because it's not ready yet.
Method object_type Return instance type 'object'.
Method overload_erased_call_targets Returns a list of all targets that match the caller after erasing types.
Method plausible_overload_call_targets Returns all overload call targets that having matching argument counts.
Method real_union Undocumented
Method refers_to_typeddict Undocumented
Method reset Undocumented
Method transform_callee_type Attempt to determine a more accurate signature for a method call.
Method try_getting_int_literals If the given expression or type corresponds to an int literal or a union of int literals, returns a list of the underlying ints. Otherwise, returns None.
Method try_infer_partial_type Try to make partial type precise from a call.
Method try_infer_partial_value_type_from_call Try to make partial type precise from a call such as 'x.append(y)'.
Method type_overrides_set Set _temporary_ type overrides for given expressions.
Method typeddict_callable Construct a reasonable type for a TypedDict type in runtime context.
Method typeddict_callable_from_context Undocumented
Method union_overload_result Accepts a list of overload signatures and attempts to match calls by destructuring the first union.
Method validate_typeddict_kwargs Undocumented
Method visit__promote_expr Undocumented
Method visit_assert_type_expr Undocumented
Method visit_assignment_expr Undocumented
Method visit_await_expr Undocumented
Method visit_bytes_expr Type check a bytes literal (trivial).
Method visit_call_expr Type check a call expression.
Method visit_call_expr_inner Undocumented
Method visit_cast_expr Type check a cast expression.
Method visit_comparison_expr Type check a comparison expression.
Method visit_complex_expr Type check a complex literal.
Method visit_conditional_expr Undocumented
Method visit_dict_expr Type check a dict expression.
Method visit_dictionary_comprehension Type check a dictionary comprehension.
Method visit_ellipsis Type check '...'.
Method visit_enum_call_expr Undocumented
Method visit_enum_index_expr Undocumented
Method visit_float_expr Type check a float literal (trivial).
Method visit_generator_expr Undocumented
Method visit_index_expr Type check an index expression (base[index]).
Method visit_index_expr_helper Undocumented
Method visit_index_with_type Analyze type of an index expression for a given type of base expression.
Method visit_int_expr Type check an integer literal (trivial).
Method visit_lambda_expr Type check lambda expression.
Method visit_list_comprehension Undocumented
Method visit_list_expr Type check a list expression [...].
Method visit_member_expr Visit member expression (of form e.id).
Method visit_name_expr Type check a name expression.
Method visit_namedtuple_expr Undocumented
Method visit_newtype_expr Undocumented
Method visit_op_expr Type check a binary operator expression.
Method visit_paramspec_expr Undocumented
Method visit_reveal_expr Type check a reveal_type expression.
Method visit_set_comprehension Undocumented
Method visit_set_expr Undocumented
Method visit_slice_expr Undocumented
Method visit_star_expr Undocumented
Method visit_str_expr Type check a string literal (trivial).
Method visit_super_expr Type check a super expression (non-lvalue).
Method visit_temp_node Undocumented
Method visit_tuple_expr Type check a tuple expression.
Method visit_tuple_slice_helper Undocumented
Method visit_type_alias_expr Right hand side of a type alias definition.
Method visit_type_application Type check a type application (expr[type, ...]).
Method visit_type_var_expr Undocumented
Method visit_type_var_tuple_expr Undocumented
Method visit_typeddict_expr Undocumented
Method visit_typeddict_index_expr Undocumented
Method visit_unary_expr Type check an unary operation ('not', '-', '+' or '~').
Method visit_yield_expr Undocumented
Method visit_yield_from_expr Undocumented
Class Variable container_args Undocumented
Class Variable item_args Undocumented
Instance Variable chk Undocumented
Instance Variable collect_line_checking_stats Undocumented
Instance Variable in_expression Undocumented
Instance Variable is_callee Undocumented
Instance Variable msg Undocumented
Instance Variable per_line_checking_time_ns Undocumented
Instance Variable plugin Undocumented
Instance Variable resolved_type Undocumented
Instance Variable strfrm_checker Undocumented
Instance Variable type_context Undocumented
Instance Variable type_overrides Undocumented
Method _super_arg_types Computes the types of the type and instance expressions in super(T, instance), or the implicit ones for zero-argument super() expressions. Returns a single type for the whole super expression when possible (for errors, anys), otherwise the pair of computed types.
def __init__(self, chk: mypy.checker.TypeChecker, msg: MessageBuilder, plugin: Plugin, per_line_checking_time_ns: dict[int, int]): (source)

Construct an expression type checker.

def accept(self, node: Expression, type_context: Type|None = None, allow_none_return: bool = False, always_allow_any: bool = False, is_callee: bool = False) -> Type: (source)

Type check a node in the given type context. If allow_none_return is True and this expression is a call, allow it to return None. This applies only to this expression and not any subexpressions.

def alias_type_in_runtime_context(self, alias: TypeAlias, *, ctx: Context, alias_definition: bool = False) -> Type: (source)

Get type of a type alias (could be generic) in a runtime expression. Note that this function can be called only if the alias appears _not_ as a target of type application, which is treated separately in the visit_type_application method. Some examples where this method is called are casts and instantiation: class LongName(Generic[T]): ... A = LongName[int] x = A() y = cast(A, ...)

def always_returns_none(self, node: Expression) -> bool: (source)

Check if `node` refers to something explicitly annotated as only returning None.

def analyze_cond_branch(self, map: dict[Expression, Type]|None, node: Expression, context: Type|None, allow_none_return: bool = False) -> Type: (source)

Undocumented

def analyze_external_member_access(self, member: str, base_type: Type, context: Context) -> Type: (source)

Analyse member access that is external, i.e. it cannot refer to private definitions. Return the result type.

def analyze_ordinary_member_access(self, e: MemberExpr, is_lvalue: bool) -> Type: (source)

Analyse member expression or member lvalue.

def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type: (source)

Undocumented

def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type: (source)

Analyze the callee X in X(...) where X is Type[item]. Return a Y that we can pass to check_call(Y, ...).

def analyze_var_ref(self, var: Var, context: Context) -> Type: (source)

Undocumented

def apply_function_plugin(self, callee: CallableType, arg_kinds: list[ArgKind], arg_types: list[Type], arg_names: Sequence[str|None]|None, formal_to_actual: list[list[int]], args: list[Expression], fullname: str, object_type: Type|None, context: Context) -> Type: (source)

Use special case logic to infer the return type of a specific named function/method. Caller must ensure that a plugin hook exists. There are two different cases: - If object_type is None, the caller must ensure that a function hook exists for fullname. - If object_type is not None, the caller must ensure that a method hook exists for fullname. Return the inferred return type.

def apply_function_signature_hook(self, callee: FunctionLike, args: list[Expression], arg_kinds: list[ArgKind], context: Context, arg_names: Sequence[str|None]|None, signature_hook: Callable[[FunctionSigContext], FunctionLike]) -> FunctionLike: (source)

Apply a plugin hook that may infer a more precise signature for a function.

def apply_generic_arguments(self, callable: CallableType, types: Sequence[Type|None], context: Context, skip_unsatisfied: bool = False) -> CallableType: (source)

Simple wrapper around mypy.applytype.apply_generic_arguments.

def apply_inferred_arguments(self, callee_type: CallableType, inferred_args: Sequence[Type|None], context: Context) -> CallableType: (source)

Apply inferred values of type arguments to a generic function. Inferred_args contains the values of function type arguments.

def apply_method_signature_hook(self, callee: FunctionLike, args: list[Expression], arg_kinds: list[ArgKind], context: Context, arg_names: Sequence[str|None]|None, object_type: Type, signature_hook: Callable[[MethodSigContext], FunctionLike]) -> FunctionLike: (source)

Apply a plugin hook that may infer a more precise signature for a method.

def apply_signature_hook(self, callee: FunctionLike, args: list[Expression], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, hook: Callable[[list[list[Expression]], CallableType], FunctionLike]) -> FunctionLike: (source)

Helper to apply a signature hook for either a function or method

def apply_type_arguments_to_callable(self, tp: Type, args: Sequence[Type], ctx: Context) -> Type: (source)

Apply type arguments to a generic callable type coming from a type object. This will first perform type arguments count checks, report the error as needed, and return the correct kind of Any. As a special case this returns Any for non-callable types, because if type object type is not callable, then an error should be already reported.

def argument_infer_context(self) -> ArgumentInferContext: (source)

Undocumented

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

Return instance type 'bool'.

def can_return_none(self, type: TypeInfo, attr_name: str) -> bool: (source)

Is the given attribute a method with a None-compatible return type? Overloads are only checked if there is an implementation.

def check_any_type_call(self, args: list[Expression], callee: Type) -> tuple[Type, Type]: (source)

Undocumented

def check_arg(self, caller_type: Type, original_caller_type: Type, caller_kind: ArgKind, callee_type: Type, n: int, m: int, callee: CallableType, object_type: Type|None, context: Context, outer_context: Context): (source)

Check the type of a single argument in a call.

def check_argument_count(self, callee: CallableType, actual_types: list[Type], actual_kinds: list[ArgKind], actual_names: Sequence[str|None]|None, formal_to_actual: list[list[int]], context: Context|None, object_type: Type|None = None, callable_name: str|None = None) -> bool: (source)

Check that there is a value for all required arguments to a function. Also check that there are no duplicate values for arguments. Report found errors using 'messages' if it's not None. If 'messages' is given, 'context' must also be given. Return False if there were any errors. Otherwise return True

def check_argument_types(self, arg_types: list[Type], arg_kinds: list[ArgKind], args: list[Expression], callee: CallableType, formal_to_actual: list[list[int]], context: Context, check_arg: ArgChecker|None = None, object_type: Type|None = None): (source)

Check argument types against a callable type. Report errors if the argument types are not compatible. The check_call docstring describes some of the arguments.

def check_awaitable_expr(self, t: Type, ctx: Context, msg: str|ErrorMessage, ignore_binder: bool = False) -> Type: (source)

Check the argument to `await` and extract the type of value. Also used by `async for` and `async with`.

def check_boolean_op(self, e: OpExpr, context: Context) -> Type: (source)

Type check a boolean operation ('and' or 'or').

def check_call(self, callee: Type, args: list[Expression], arg_kinds: list[ArgKind], context: Context, arg_names: Sequence[str|None]|None = None, callable_node: Expression|None = None, callable_name: str|None = None, object_type: Type|None = None) -> tuple[Type, Type]: (source)

Type check a call. Also infer type arguments if the callee is a generic function. Return (result type, inferred callee type). Arguments: callee: type of the called value args: actual argument expressions arg_kinds: contains nodes.ARG_* constant for each argument in args describing whether the argument is positional, *arg, etc. context: current expression context, used for inference. arg_names: names of arguments (optional) callable_node: associate the inferred callable type to this node, if specified callable_name: Fully-qualified name of the function/method to call, or None if unavailable (examples: 'builtins.open', 'typing.Mapping.get') object_type: If callable_name refers to a method, the type of the object on which the method is being called

def check_call_expr_with_callee_type(self, callee_type: Type, e: CallExpr, callable_name: str|None, object_type: Type|None, member: str|None = None) -> Type: (source)

Type check call expression. The callee_type should be used as the type of callee expression. In particular, in case of a union type this can be a particular item of the union, so that we can apply plugin hooks to each item. The 'member', 'callable_name' and 'object_type' are only used to call plugin hooks. If 'callable_name' is None but 'member' is not None (member call), try constructing 'callable_name' using 'object_type' (the base type on which the method is called), for example 'typing.Mapping.get'.

def check_callable_call(self, callee: CallableType, args: list[Expression], arg_kinds: list[ArgKind], context: Context, arg_names: Sequence[str|None]|None, callable_node: Expression|None, callable_name: str|None, object_type: Type|None) -> tuple[Type, Type]: (source)

Type check a call that targets a callable value. See the docstring of check_call for more information.

Check the for_comp part of comprehensions. That is the part from 'for': ... for x in y if z Note: This adds the type information derived from the condlists to the current binder.

def check_for_extra_actual_arguments(self, callee: CallableType, actual_types: list[Type], actual_kinds: list[ArgKind], actual_names: Sequence[str|None]|None, all_actuals: dict[int, int], context: Context) -> tuple[bool, bool]: (source)

Check for extra actual arguments. Return tuple (was everything ok, was there an extra keyword argument error [used to avoid duplicate errors]).

def check_generator_or_comprehension(self, gen: GeneratorExpr, type_name: str, id_for_messages: str, additional_args: list[Type]|None = None) -> Type: (source)

Type check a generator expression or a list comprehension.

def check_list_multiply(self, e: OpExpr) -> Type: (source)

Type check an expression of form '[...] * e'. Type inference is special-cased for this common construct.

def check_lst_expr(self, e: (ListExpr|SetExpr)|TupleExpr, fullname: str, tag: str) -> Type: (source)

Undocumented

def check_method_call(self, method_name: str, base_type: Type, method_type: Type, args: list[Expression], arg_kinds: list[ArgKind], context: Context) -> tuple[Type, Type]: (source)

Type check a call to a method with the given name and type on an object. Return tuple (result type, inferred method type).

def check_method_call_by_name(self, method: str, base_type: Type, args: list[Expression], arg_kinds: list[ArgKind], context: Context, original_type: Type|None = None) -> tuple[Type, Type]: (source)

Type check a call to a named method on an object. Return tuple (result type, inferred method type). The 'original_type' is used for error messages.

def check_op(self, method: str, base_type: Type, arg: Expression, context: Context, allow_reverse: bool = False) -> tuple[Type, Type]: (source)

Type check a binary operation which maps to a method call. Return tuple (result type, inferred operator method type).

def check_op_reversible(self, op_name: str, left_type: Type, left_expr: Expression, right_type: Type, right_expr: Expression, context: Context) -> tuple[Type, Type]: (source)

Undocumented

def check_overload_call(self, callee: Overloaded, args: list[Expression], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, callable_name: str|None, object_type: Type|None, context: Context) -> tuple[Type, Type]: (source)

Checks a call to an overloaded function.

def check_protocol_issubclass(self, e: CallExpr): (source)

Undocumented

def check_runtime_protocol_test(self, e: CallExpr): (source)

Undocumented

def check_str_format_call(self, e: CallExpr): (source)

More precise type checking for str.format() calls on literals.

def check_typeddict_call(self, callee: TypedDictType, arg_kinds: list[ArgKind], arg_names: Sequence[str|None], args: list[Expression], context: Context, orig_callee: Type|None) -> Type: (source)

Undocumented

def check_typeddict_call_with_dict(self, callee: TypedDictType, kwargs: DictExpr, context: Context, orig_callee: Type|None) -> Type: (source)

Undocumented

def check_typeddict_call_with_kwargs(self, callee: TypedDictType, kwargs: dict[str, Expression], context: Context, orig_callee: Type|None) -> Type: (source)

Undocumented

def check_typeddict_literal_in_context(self, e: DictExpr, typeddict_context: TypedDictType) -> Type: (source)

Undocumented

def check_union_call(self, callee: UnionType, args: list[Expression], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, context: Context) -> tuple[Type, Type]: (source)

Undocumented

def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type: (source)

Type check calling a member expression where the base type is a union.

def check_union_method_call_by_name(self, method: str, base_type: UnionType, args: list[Expression], arg_kinds: list[ArgKind], context: Context, original_type: Type|None = None) -> tuple[Type, Type]: (source)

Type check a call to a named method on an object with union type. This essentially checks the call using check_method_call_by_name() for each union item and unions the result. We do this to allow plugins to act on individual union items.

def combine_function_signatures(self, types: list[ProperType]) -> AnyType|CallableType: (source)

Accepts a list of function signatures and attempts to combine them together into a new CallableType consisting of the union of all of the given arguments and return types. If there is at least one non-callable type, return Any (this can happen if there is an ambiguity because of Any in arguments).

def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType: (source)

Concatenate two fixed length tuples.

def dangerous_comparison(self, left: Type, right: Type, original_container: Type|None = None, *, prefer_literal: bool = True) -> bool: (source)

Check for dangerous non-overlapping comparisons like 42 == 'no'. The original_container is the original container type for 'in' checks (and None for equality checks). Rules: * X and None are overlapping even in strict-optional mode. This is to allow 'assert x is not None' for x defined as 'x = None # type: str' in class body (otherwise mypy itself would have couple dozen errors because of this). * Optional[X] and Optional[Y] are non-overlapping if X and Y are non-overlapping, although technically None is overlap, it is most likely an error. * Any overlaps with everything, i.e. always safe. * Special case: b'abc' in b'cde' is safe.

def defn_returns_none(self, defn: SymbolNode|None) -> bool: (source)

Check if `defn` can _only_ return None.

def erased_signature_similarity(self, arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, args: list[Expression], callee: CallableType, context: Context) -> bool: (source)

Determine whether arguments could match the signature at runtime, after erasing types.

def fast_container_type(self, e: (ListExpr|SetExpr)|TupleExpr, container_fullname: str) -> Type|None: (source)

Fast path to determine the type of a list or set literal, based on the list of entries. This mostly impacts large module-level constant definitions. Limitations: - no active type context - no star expressions - the joined type of all entries must be an Instance or Tuple type

def fast_dict_type(self, e: DictExpr) -> Type|None: (source)

Fast path to determine the type of a dict literal, based on the list of entries. This mostly impacts large module-level constant definitions. Limitations: - no active type context - only supported star expressions are other dict instances - the joined types of all keys and values must be Instance or Tuple types

def find_partial_type_ref_fast_path(self, expr: Expression) -> Type|None: (source)

If expression has a partial generic type, return it without additional checks. In particular, this does not generate an error about a missing annotation. Otherwise, return None.

def find_typeddict_context(self, context: Type|None, dict_expr: DictExpr) -> list[TypedDictType]: (source)

Undocumented

def get_arg_infer_passes(self, arg_types: list[Type], formal_to_actual: list[list[int]], num_actuals: int) -> list[int]: (source)

Return pass numbers for args for two-pass argument type inference. For each actual, the pass number is either 1 (first pass) or 2 (second pass). Two-pass argument type inference primarily lets us infer types of lambdas more effectively.

def get_partial_self_var(self, expr: MemberExpr) -> Var|None: (source)

Get variable node for a partial self attribute. If the expression is not a self attribute, or attribute is not variable, or variable is not partial, return None.

def get_partial_var(self, ref: RefExpr) -> tuple[Var, dict[Var, Context]]|None: (source)

Undocumented

def has_member(self, typ: Type, member: str) -> bool: (source)

Does type have member with the given name?

def infer_arg_types_in_context(self, callee: CallableType, args: list[Expression], arg_kinds: list[ArgKind], formal_to_actual: list[list[int]]) -> list[Type]: (source)

Infer argument expression types using a callable type as context. For example, if callee argument 2 has type List[int], infer the argument expression with List[int] type context. Returns the inferred types of *actual arguments*.

def infer_arg_types_in_empty_context(self, args: list[Expression]) -> list[Type]: (source)

Infer argument expression types in an empty context. In short, we basically recurse on each argument without considering in what context the argument was called.

def infer_function_type_arguments(self, callee_type: CallableType, args: list[Expression], arg_kinds: list[ArgKind], formal_to_actual: list[list[int]], context: Context) -> CallableType: (source)

Infer the type arguments for a generic callee type. Infer based on the types of arguments. Return a derived callable type that has the arguments applied.

def infer_function_type_arguments_pass2(self, callee_type: CallableType, args: list[Expression], arg_kinds: list[ArgKind], formal_to_actual: list[list[int]], old_inferred_args: Sequence[Type|None], context: Context) -> tuple[CallableType, list[Type|None]]: (source)

Perform second pass of generic function type argument inference. The second pass is needed for arguments with types such as Callable[[T], S], where both T and S are type variables, when the actual argument is a lambda with inferred types. The idea is to infer the type variable T in the first pass (based on the types of other arguments). This lets us infer the argument and return type of the lambda expression and thus also the type variable S in this second pass. Return (the callee with type vars applied, inferred actual arg types).

def infer_function_type_arguments_using_context(self, callable: CallableType, error_context: Context) -> CallableType: (source)

Unify callable return type to type context to infer type vars. For example, if the return type is set[t] where 't' is a type variable of callable, and if the context is set[int], return callable modified by substituting 't' with 'int'.

def infer_lambda_type_using_context(self, e: LambdaExpr) -> tuple[CallableType|None, CallableType|None]: (source)

Try to infer lambda expression type using context. Return None if could not infer type. The second item in the return type is the type_override parameter for check_func_item.

def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type: (source)

Analyzes the given literal expression and determines if we should be inferring an Instance type, a Literal[...] type, or an Instance that remembers the original literal. We... 1. ...Infer a normal Instance in most circumstances. 2. ...Infer a Literal[...] if we're in a literal context. For example, if we were analyzing the "3" in "foo(3)" where "foo" has a signature of "def foo(Literal[3]) -> None", we'd want to infer that the "3" has a type of Literal[3] instead of Instance. 3. ...Infer an Instance that remembers the original Literal if we're declaring a Final variable with an inferred type -- for example, "bar" in "bar: Final = 3" would be assigned an Instance that remembers it originated from a '3'. See the comments in Instance's constructor for more details.

def infer_more_unions_for_recursive_type(self, type_context: Type) -> bool: (source)

Adjust type inference of unions if type context has a recursive type. Return the old state. The caller must assign it to type_state.infer_unions afterwards. This is a hack to better support inference for recursive types. Note: This is performance-sensitive and must not be a context manager until mypyc supports them better.

def infer_overload_return_type(self, plausible_targets: list[CallableType], args: list[Expression], arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, callable_name: str|None, object_type: Type|None, context: Context) -> tuple[Type, Type]|None: (source)

Attempts to find the first matching callable from the given list. If a match is found, returns a tuple containing the result type and the inferred callee type. (This tuple is meant to be eventually returned by check_call.) If multiple targets match due to ambiguous Any parameters, returns (AnyType, AnyType). If no targets match, returns None. Assumes all of the given targets have argument counts compatible with the caller.

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

Undocumented

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

Is a type valid as a **kwargs argument?

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

Is a type valid as a *args argument?

def match_typeddict_call_with_dict(self, callee: TypedDictType, kwargs: DictExpr, context: Context) -> bool: (source)

Undocumented

def method_fullname(self, object_type: Type, method_name: str) -> str|None: (source)

Convert a method name to a fully qualified name, based on the type of the object that it is invoked on. Return `None` if the name of `object_type` cannot be determined.

def missing_classvar_callable_note(self, object_type: Type, callable_name: str, context: Context): (source)

Undocumented

def module_type(self, node: MypyFile) -> Instance: (source)

Undocumented

def named_type(self, name: str) -> Instance: (source)

Return an instance type with type given by the name and no type arguments. Alias for TypeChecker.named_type.

@overload
def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type:
@overload
def narrow_type_from_binder(self, expr: Expression, known_type: Type, skip_non_overlapping: bool) -> Type|None:
(source)

Narrow down a known type of expression using information in conditional type binder. If 'skip_non_overlapping' is True, return None if the type and restriction are non-overlapping.

def nonliteral_tuple_index_helper(self, left_type: TupleType, index: Expression) -> Type: (source)

Undocumented

def not_ready_callback(self, name: str, context: Context): (source)

Called when we can't infer the type of a variable because it's not ready yet. Either defer type checking of the enclosing function to the next pass or report an error.

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

Return instance type 'object'.

def overload_erased_call_targets(self, plausible_targets: list[CallableType], arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, args: list[Expression], context: Context) -> list[CallableType]: (source)

Returns a list of all targets that match the caller after erasing types. Assumes all of the given targets have argument counts compatible with the caller.

def plausible_overload_call_targets(self, arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, overload: Overloaded) -> list[CallableType]: (source)

Returns all overload call targets that having matching argument counts. If the given args contains a star-arg (*arg or **kwarg argument), this method will ensure all star-arg overloads appear at the start of the list, instead of their usual location. The only exception is if the starred argument is something like a Tuple or a NamedTuple, which has a definitive "shape". If so, we don't move the corresponding alternative to the front since we can infer a more precise match using the original order.

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

Undocumented

def refers_to_typeddict(self, base: Expression) -> bool: (source)

Undocumented

def reset(self): (source)

Undocumented

def transform_callee_type(self, callable_name: str|None, callee: Type, args: list[Expression], arg_kinds: list[ArgKind], context: Context, arg_names: Sequence[str|None]|None = None, object_type: Type|None = None) -> Type: (source)

Attempt to determine a more accurate signature for a method call. This is done by looking up and applying a method signature hook (if one exists for the given method name). If no matching method signature hook is found, callee is returned unmodified. The same happens if the arguments refer to a non-method callable (this is allowed so that the code calling transform_callee_type needs to perform fewer boilerplate checks). Note: this method is *not* called automatically as part of check_call, because in some cases check_call is called multiple times while checking a single call (for example when dealing with overloads). Instead, this method needs to be called explicitly (if appropriate) before the signature is passed to check_call.

def try_getting_int_literals(self, index: Expression) -> list[int]|None: (source)

If the given expression or type corresponds to an int literal or a union of int literals, returns a list of the underlying ints. Otherwise, returns None. Specifically, this function is guaranteed to return a list with one or more ints if one one the following is true: 1. 'expr' is a IntExpr or a UnaryExpr backed by an IntExpr 2. 'typ' is a LiteralType containing an int 3. 'typ' is a UnionType containing only LiteralType of ints

def try_infer_partial_type(self, e: CallExpr): (source)

Try to make partial type precise from a call.

def try_infer_partial_value_type_from_call(self, e: CallExpr, methodname: str, var: Var) -> Instance|None: (source)

Try to make partial type precise from a call such as 'x.append(y)'.

@contextmanager
def type_overrides_set(self, exprs: Sequence[Expression], overrides: Sequence[Type]) -> Iterator[None]: (source)

Set _temporary_ type overrides for given expressions.

def typeddict_callable(self, info: TypeInfo) -> CallableType: (source)

Construct a reasonable type for a TypedDict type in runtime context. If it appears as a callee, it will be special-cased anyway, e.g. it is also allowed to accept a single positional argument if it is a dict literal. Note it is not safe to move this to type_object_type() since it will crash on plugin-generated TypedDicts, that may not have the special_alias.

def typeddict_callable_from_context(self, callee: TypedDictType) -> CallableType: (source)

Undocumented

def union_overload_result(self, plausible_targets: list[CallableType], args: list[Expression], arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: Sequence[str|None]|None, callable_name: str|None, object_type: Type|None, context: Context, level: int = 0) -> list[tuple[Type, Type]]|None: (source)

Accepts a list of overload signatures and attempts to match calls by destructuring the first union. Return a list of (<return type>, <inferred variant type>) if call succeeds for every item of the desctructured union. Returns None if there is no match.

def validate_typeddict_kwargs(self, kwargs: DictExpr) -> dict[str, Expression]|None: (source)

Undocumented

def visit__promote_expr(self, e: PromoteExpr) -> Type: (source)
def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type: (source)
def visit_assignment_expr(self, e: AssignmentExpr) -> Type: (source)
def visit_await_expr(self, e: AwaitExpr, allow_none_return: bool = False) -> Type: (source)
def visit_bytes_expr(self, e: BytesExpr) -> Type: (source)

Type check a bytes literal (trivial).

def visit_call_expr(self, e: CallExpr, allow_none_return: bool = False) -> Type: (source)

Type check a call expression.

def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) -> Type: (source)

Undocumented

def visit_cast_expr(self, expr: CastExpr) -> Type: (source)

Type check a cast expression.

def visit_comparison_expr(self, e: ComparisonExpr) -> Type: (source)

Type check a comparison expression. Comparison expressions are type checked consecutive-pair-wise That is, 'a < b > c == d' is check as 'a < b and b > c and c == d'

def visit_complex_expr(self, e: ComplexExpr) -> Type: (source)

Type check a complex literal.

def visit_conditional_expr(self, e: ConditionalExpr, allow_none_return: bool = False) -> Type: (source)
def visit_dict_expr(self, e: DictExpr) -> Type: (source)

Type check a dict expression. Translate it into a call to dict(), with provisions for **expr.

def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: (source)

Type check a dictionary comprehension.

def visit_ellipsis(self, e: EllipsisExpr) -> Type: (source)

Type check '...'.

def visit_enum_call_expr(self, e: EnumCallExpr) -> Type: (source)
def visit_enum_index_expr(self, enum_type: TypeInfo, index: Expression, context: Context) -> Type: (source)

Undocumented

def visit_float_expr(self, e: FloatExpr) -> Type: (source)

Type check a float literal (trivial).

def visit_generator_expr(self, e: GeneratorExpr) -> Type: (source)
def visit_index_expr(self, e: IndexExpr) -> Type: (source)

Type check an index expression (base[index]). It may also represent type application.

def visit_index_expr_helper(self, e: IndexExpr) -> Type: (source)

Undocumented

def visit_index_with_type(self, left_type: Type, e: IndexExpr, original_type: ProperType|None = None) -> Type: (source)

Analyze type of an index expression for a given type of base expression. The 'original_type' is used for error messages (currently used for union types).

def visit_int_expr(self, e: IntExpr) -> Type: (source)

Type check an integer literal (trivial).

def visit_lambda_expr(self, e: LambdaExpr) -> Type: (source)

Type check lambda expression.

def visit_list_comprehension(self, e: ListComprehension) -> Type: (source)
def visit_list_expr(self, e: ListExpr) -> Type: (source)

Type check a list expression [...].

def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type: (source)

Visit member expression (of form e.id).

def visit_name_expr(self, e: NameExpr) -> Type: (source)

Type check a name expression. It can be of any kind: local, member or global.

def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type: (source)
def visit_newtype_expr(self, e: NewTypeExpr) -> Type: (source)
def visit_op_expr(self, e: OpExpr) -> Type: (source)

Type check a binary operator expression.

def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type: (source)
def visit_reveal_expr(self, expr: RevealExpr) -> Type: (source)

Type check a reveal_type expression.

def visit_set_comprehension(self, e: SetComprehension) -> Type: (source)
def visit_set_expr(self, e: SetExpr) -> Type: (source)
def visit_slice_expr(self, e: SliceExpr) -> Type: (source)
def visit_star_expr(self, e: StarExpr) -> Type: (source)
def visit_str_expr(self, e: StrExpr) -> Type: (source)

Type check a string literal (trivial).

def visit_super_expr(self, e: SuperExpr) -> Type: (source)

Type check a super expression (non-lvalue).

def visit_temp_node(self, e: TempNode) -> Type: (source)
def visit_tuple_expr(self, e: TupleExpr) -> Type: (source)

Type check a tuple expression.

def visit_tuple_slice_helper(self, left_type: TupleType, slic: SliceExpr) -> Type: (source)

Undocumented

def visit_type_alias_expr(self, alias: TypeAliasExpr) -> Type: (source)

Right hand side of a type alias definition. It has the same type as if the alias itself was used in a runtime context. For example, here: A = reveal_type(List[T]) reveal_type(A) both `reveal_type` instances will reveal the same type `def (...) -> builtins.list[Any]`. Note that type variables are implicitly substituted with `Any`.

def visit_type_application(self, tapp: TypeApplication) -> Type: (source)

Type check a type application (expr[type, ...]). There are two different options here, depending on whether expr refers to a type alias or directly to a generic class. In the first case we need to use a dedicated function typeanal.expand_type_alias(). This is due to some differences in how type arguments are applied and checked.

def visit_type_var_expr(self, e: TypeVarExpr) -> Type: (source)
def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> Type: (source)
def visit_typeddict_expr(self, e: TypedDictExpr) -> Type: (source)
def visit_typeddict_index_expr(self, td_type: TypedDictType, index: Expression, setitem: bool = False) -> Type: (source)

Undocumented

def visit_unary_expr(self, e: UnaryExpr) -> Type: (source)

Type check an unary operation ('not', '-', '+' or '~').

def visit_yield_expr(self, e: YieldExpr) -> Type: (source)
def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = False) -> Type: (source)
container_args: ClassVar[dict[str, dict[str, list[str]]]] = (source)

Undocumented

Undocumented

Undocumented

collect_line_checking_stats = (source)

Undocumented

in_expression: bool = (source)

Undocumented

is_callee = (source)

Undocumented

Undocumented

per_line_checking_time_ns = (source)

Undocumented

Undocumented

resolved_type: dict = (source)

Undocumented

strfrm_checker = (source)

Undocumented

type_context: list = (source)

Undocumented

type_overrides: dict[Expression, Type] = (source)

Undocumented

def _super_arg_types(self, e: SuperExpr) -> Type|tuple[Type, Type]: (source)

Computes the types of the type and instance expressions in super(T, instance), or the implicit ones for zero-argument super() expressions. Returns a single type for the whole super expression when possible (for errors, anys), otherwise the pair of computed types.