module documentation

Mypy type checker.

Class CheckerScope No class docstring; 0/1 instance variable, 2/8 methods documented
Class CollectArgTypeVarTypes Collects the non-nested argument types in a set.
Class DeferredNode Undocumented
Class DisjointDict An variation of the union-find algorithm/data structure where instead of keeping track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint.
Class FineGrainedDeferredNode Undocumented
Class InvalidInferredTypes Find type components that are not valid for an inferred type.
Class PartialTypeScope Undocumented
Class SetNothingToAny Replace all ambiguous <nothing> types with Any (to avoid spurious extra errors).
Class TypeChecker Mypy type checker.
Class TypeRange Undocumented
Class TypeTransformVisitor Undocumented
Function and_conditional_maps Calculate what information we can learn from the truth of (e1 and e2) in terms of the information that we can learn from the truth of e1 and the truth of e2.
Function are_argument_counts_overlapping Can a single call match both t and s, based just on positional argument counts?
Function builtin_item_type Get the item type of a builtin container.
Function collapse_walrus If an expression is an AssignmentExpr, pull out the assignment target.
Function conditional_types Takes in the current type and a proposed type of an expression.
Function conditional_types_to_typemaps Undocumented
Function convert_to_typetype Undocumented
Function detach_callable Ensures that the callable's type variables are 'detached' and independent of the context.
Function expand_func Undocumented
Function flatten Flatten a nested sequence of tuples/lists into one list of nodes.
Function flatten_types Flatten a nested sequence of tuples into one list of nodes.
Function gen_unique_name Generate a name that does not appear in table by appending numbers to base.
Function get_property_type Undocumented
Function group_comparison_operands Group a series of comparison operands together chained by any operand in the 'operators_to_group' set. All other pairwise operands are kept in groups of size 2.
Function has_bool_item Return True if type is 'bool' or a union with a 'bool' item.
Function infer_operator_assignment_method Determine if operator assignment on given value type is in-place, and the method name.
Function is_false_literal Returns true if this expression is the 'False' literal/keyword.
Function is_literal_none Returns true if this expression is the 'None' literal/keyword.
Function is_literal_not_implemented Undocumented
Function is_more_general_arg_prefix Does t have wider arguments than s?
Function is_node_static Find out if a node describes a static function method.
Function is_overlapping_types_no_promote_no_uninhabited Undocumented
Function is_private Check if node is private to class definition.
Function is_property Undocumented
Function is_same_arg_prefix Undocumented
Function is_static Undocumented
Function is_string_literal Undocumented
Function is_subtype_no_promote Undocumented
Function is_true_literal Returns true if this expression is the 'True' literal/keyword.
Function is_typed_callable Undocumented
Function is_unsafe_overlapping_overload_signatures Check if two overloaded signatures are unsafely overlapping or partially overlapping.
Function is_untyped_decorator Undocumented
Function is_valid_inferred_type Is an inferred type valid and needs no further refinement?
Function or_conditional_maps Calculate what information we can learn from the truth of (e1 or e2) in terms of the information that we can learn from the truth of e1 and the truth of e2.
Function overload_can_never_match Check if the 'other' method can never be matched due to 'signature'.
Function reduce_conditional_maps Reduces a list containing pairs of if/else TypeMaps into a single pair.
Constant DEFAULT_LAST_PASS Undocumented
Type Variable T Undocumented
Type Variable TKey Undocumented
Type Variable TValue Undocumented
Type Alias DeferredNodeType Undocumented
Type Alias FineGrainedDeferredNodeType Undocumented
Type Alias TypeMap Undocumented
def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap: (source)

Calculate what information we can learn from the truth of (e1 and e2) in terms of the information that we can learn from the truth of e1 and the truth of e2.

def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool: (source)

Can a single call match both t and s, based just on positional argument counts?

def builtin_item_type(tp: Type) -> Type|None: (source)

Get the item type of a builtin container. If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict) or if the container is not parameterized (like List or List[Any]) return None. This function is used to narrow optional types in situations like this: x: Optional[int] if x in (1, 2, 3): x + 42 # OK Note: this is only OK for built-in containers, where we know the behavior of __contains__.

def collapse_walrus(e: Expression) -> Expression: (source)

If an expression is an AssignmentExpr, pull out the assignment target. We don't make any attempt to pull out all the targets in code like `x := (y := z)`. We could support narrowing those if that sort of code turns out to be common.

@overload
def conditional_types(current_type: Type, proposed_type_ranges: list[TypeRange]|None, default: None = None) -> tuple[Type|None, Type|None]:
@overload
def conditional_types(current_type: Type, proposed_type_ranges: list[TypeRange]|None, default: Type) -> tuple[Type, Type]:
(source)

Takes in the current type and a proposed type of an expression. Returns a 2-tuple: The first element is the proposed type, if the expression can be the proposed type. The second element is the type it would hold if it was not the proposed type, if any. UninhabitedType means unreachable. None means no new information can be inferred. If default is set it is returned instead.

def conditional_types_to_typemaps(expr: Expression, yes_type: Type|None, no_type: Type|None) -> tuple[TypeMap, TypeMap]: (source)

Undocumented

def convert_to_typetype(type_map: TypeMap) -> TypeMap: (source)

Undocumented

def detach_callable(typ: CallableType) -> CallableType: (source)

Ensures that the callable's type variables are 'detached' and independent of the context. A callable normally keeps track of the type variables it uses within its 'variables' field. However, if the callable is from a method and that method is using a class type variable, the callable will not keep track of that type variable since it belongs to the class. This function will traverse the callable and find all used type vars and add them to the variables field if it isn't already present. The caller can then unify on all type variables whether or not the callable is originally from a class or not.

def expand_func(defn: FuncItem, map: dict[TypeVarId, Type]) -> FuncItem: (source)

Undocumented

Flatten a nested sequence of tuples/lists into one list of nodes.

def flatten_types(t: Type) -> list[Type]: (source)

Flatten a nested sequence of tuples into one list of nodes.

def gen_unique_name(base: str, table: SymbolTable) -> str: (source)

Generate a name that does not appear in table by appending numbers to base.

def get_property_type(t: ProperType) -> ProperType: (source)

Undocumented

def group_comparison_operands(pairwise_comparisons: Iterable[tuple[str, Expression, Expression]], operand_to_literal_hash: Mapping[int, Key], operators_to_group: set[str]) -> list[tuple[str, list[int]]]: (source)

Group a series of comparison operands together chained by any operand in the 'operators_to_group' set. All other pairwise operands are kept in groups of size 2. For example, suppose we have the input comparison expression: x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8 If we get these expressions in a pairwise way (e.g. by calling ComparisionExpr's 'pairwise()' method), we get the following as input: [('==', x0, x1), ('==', x1, x2), ('<', x2, x3), ('<', x3, x4), ('is', x4, x5), ('is', x5, x6), ('is not', x6, x7), ('is not', x7, x8)] If `operators_to_group` is the set {'==', 'is'}, this function will produce the following "simplified operator list": [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]), ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])] Note that (a) we yield *indices* to the operands rather then the operand expressions themselves and that (b) operands used in a consecutive chain of '==' or 'is' are grouped together. If two of these chains happen to contain operands with the same underlying literal hash (e.g. are assignable and correspond to the same expression), we combine those chains together. For example, if we had: same == x < y == same ...and if 'operand_to_literal_hash' contained the same values for the indices 0 and 3, we'd produce the following output: [("==", [0, 1, 2, 3]), ("<", [1, 2])] But if the 'operand_to_literal_hash' did *not* contain an entry, we'd instead default to returning: [("==", [0, 1]), ("<", [1, 2]), ("==", [2, 3])] This function is currently only used to assist with type-narrowing refinements and is extracted out to a helper function so we can unit test it.

def has_bool_item(typ: ProperType) -> bool: (source)

Return True if type is 'bool' or a union with a 'bool' item.

def infer_operator_assignment_method(typ: Type, operator: str) -> tuple[bool, str]: (source)

Determine if operator assignment on given value type is in-place, and the method name. For example, if operator is '+', return (True, '__iadd__') or (False, '__add__') depending on which method is supported by the type.

def is_false_literal(n: Expression) -> bool: (source)

Returns true if this expression is the 'False' literal/keyword.

def is_literal_none(n: Expression) -> bool: (source)

Returns true if this expression is the 'None' literal/keyword.

def is_literal_not_implemented(n: Expression) -> bool: (source)

Undocumented

def is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool: (source)

Does t have wider arguments than s?

def is_node_static(node: Node|None) -> bool|None: (source)

Find out if a node describes a static function method.

def is_overlapping_types_no_promote_no_uninhabited(left: Type, right: Type) -> bool: (source)

Undocumented

def is_private(node_name: str) -> bool: (source)

Check if node is private to class definition.

def is_property(defn: SymbolNode) -> bool: (source)

Undocumented

def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool: (source)

Undocumented

def is_static(func: FuncBase|Decorator) -> bool: (source)

Undocumented

def is_string_literal(typ: Type) -> bool: (source)

Undocumented

def is_subtype_no_promote(left: Type, right: Type) -> bool: (source)

Undocumented

def is_true_literal(n: Expression) -> bool: (source)

Returns true if this expression is the 'True' literal/keyword.

def is_typed_callable(c: Type|None) -> bool: (source)

Undocumented

def is_unsafe_overlapping_overload_signatures(signature: CallableType, other: CallableType) -> bool: (source)

Check if two overloaded signatures are unsafely overlapping or partially overlapping. We consider two functions 's' and 't' to be unsafely overlapping if both of the following are true: 1. s's parameters are all more precise or partially overlapping with t's 2. s's return type is NOT a subtype of t's. Assumes that 'signature' appears earlier in the list of overload alternatives then 'other' and that their argument counts are overlapping.

def is_untyped_decorator(typ: Type|None) -> bool: (source)

Undocumented

def is_valid_inferred_type(typ: Type, is_lvalue_final: bool = False) -> bool: (source)

Is an inferred type valid and needs no further refinement? Examples of invalid types include the None type (when we are not assigning None to a final lvalue) or List[<uninhabited>]. When not doing strict Optional checking, all types containing None are invalid. When doing strict Optional checking, only None and types that are incompletely defined (i.e. contain UninhabitedType) are invalid.

def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap: (source)

Calculate what information we can learn from the truth of (e1 or e2) in terms of the information that we can learn from the truth of e1 and the truth of e2.

def overload_can_never_match(signature: CallableType, other: CallableType) -> bool: (source)

Check if the 'other' method can never be matched due to 'signature'. This can happen if signature's parameters are all strictly broader then other's parameters. Assumes that both signatures have overlapping argument counts.

def reduce_conditional_maps(type_maps: list[tuple[TypeMap, TypeMap]]) -> tuple[TypeMap, TypeMap]: (source)

Reduces a list containing pairs of if/else TypeMaps into a single pair. We "and" together all of the if TypeMaps and "or" together the else TypeMaps. So for example, if we had the input: [ ({x: TypeIfX, shared: TypeIfShared1}, {x: TypeElseX, shared: TypeElseShared1}), ({y: TypeIfY, shared: TypeIfShared2}, {y: TypeElseY, shared: TypeElseShared2}), ] ...we'd return the output: ( {x: TypeIfX, y: TypeIfY, shared: PseudoIntersection[TypeIfShared1, TypeIfShared2]}, {shared: Union[TypeElseShared1, TypeElseShared2]}, ) ...where "PseudoIntersection[X, Y] == Y" because mypy actually doesn't understand intersections yet, so we settle for just arbitrarily picking the right expr's type. We only retain the shared expression in the 'else' case because we don't actually know whether x was refined or y was refined -- only just that one of the two was refined.

DEFAULT_LAST_PASS: int = (source)

Undocumented

Value
1

Undocumented

Value
TypeVar('T')

Undocumented

Value
TypeVar('TKey')

Undocumented

Value
TypeVar('TValue')
DeferredNodeType: _TypeAlias = (source)
FineGrainedDeferredNodeType: _TypeAlias = (source)

Undocumented

Value
Union[FuncDef, MypyFile, OverloadedFuncDef]
TypeMap: _TypeAlias = (source)

Undocumented

Value
Optional[Dict[Expression, Type]]