module documentation
(source)

Miscellaneous type operations and helpers for use during type checking.

NOTE: These must not be accessed from mypy.nodes or mypy.types to avoid import
cycles. These must not be called from the semantic analysis main pass since these may assume that MROs are ready.
Class ​Type​Var​Extractor Undocumented
Function bind​_self Return a copy of method, with the type of its first parameter (usually self or cls) bound to original_type.
Function callable​_corresponding​_argument Return the argument a function that corresponds to model
Function callable​_type Undocumented
Function class​_callable Create a type object type based on the signature of __init__.
Function coerce​_to​_literal Recursively converts any Instances that have a last_known_value or are instances of enum types with a single value into the corresponding LiteralType.
Function custom​_special​_method Does this type have a custom special method such as __format__() or __eq__()?
Function erase​_def​_to​_union​_or​_bound Undocumented
Function erase​_to​_bound Undocumented
Function erase​_to​_union​_or​_bound Undocumented
Function false​_only Restricted version of t with only False-ish values
Function function​_type Undocumented
Function get​_enum​_values Return the list of values for an Enum.
Function get​_type​_vars Undocumented
Function is​_literal​_type​_like Returns 'true' if the given type context is potentially either a LiteralType, a Union of LiteralType, or something similar.
Function is​_recursive​_pair Is this a pair of recursive type aliases?
Function is​_redundant​_literal​_instance Undocumented
Function is​_simple​_literal Whether a type is a simple enough literal to allow for fast Union simplification
Function is​_singleton​_type Returns 'true' if this type is a "singleton type" -- if there exists exactly only one runtime value associated with this type.
Function make​_simplified​_union Build union type with redundant union items removed.
Function map​_type​_from​_supertype Map type variables in a type defined in a supertype context to be valid in the subtype context. Assume that the result is unique; if more than one type is possible, return one of the alternatives.
Function supported​_self​_type Is this a supported kind of explicit self-types?
Function true​_only Restricted version of t with only True-ish values
Function true​_or​_false Unrestricted version of t with both True-ish and False-ish values
Function try​_contracting​_literals​_in​_union Contracts any literal types back into a sum type if possible.
Function try​_expanding​_sum​_type​_to​_union Attempts to recursively expand any enum Instances with the given target_fullname into a Union of all of its component LiteralTypes.
Function try​_getting​_instance​_fallback Returns the Instance fallback for this type if one exists.
Function try​_getting​_int​_literals​_from​_type 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.
Function try​_getting​_literals​_from​_type No summary
Function try​_getting​_str​_literals If the given expression or type corresponds to a string literal or a union of string literals, returns a list of the underlying strings. Otherwise, returns None.
Function try​_getting​_str​_literals​_from​_type If the given expression or type corresponds to a string Literal or a union of string Literals, returns a list of the underlying strings. Otherwise, returns None.
Function tuple​_fallback Return fallback type for a tuple.
Function type​_object​_type​_from​_function Undocumented
Constant F Undocumented
Constant T Undocumented
Function _get​_type​_special​_method​_bool​_ret​_type Undocumented
def bind_self(method, original_type=None, is_classmethod=False): (source)

Return a copy of method, with the type of its first parameter (usually self or cls) bound to original_type.

If the type of self is a generic type (T, or Type[T] for classmethods), instantiate every occurrence of type with original_type in the rest of the signature and in the return type.

original_type is the type of E in the expression E.copy(). It is None in compatibility checks. In this case we treat it as the erasure of the declared type of self.

This way we can express "the type of self". For example:

T = TypeVar('T', bound='A') class A:

def copy(self: T) -> T: ...

class B(A): pass

b = B().copy() # type: B

Parameters
method:FUndocumented
original​_type:Optional[Type]Undocumented
is​_classmethod:boolUndocumented
Returns
FUndocumented
def callable_corresponding_argument(typ, model): (source)
Return the argument a function that corresponds to model
Parameters
typ:CallableTypeUndocumented
model:FormalArgumentUndocumented
Returns
Optional[FormalArgument]Undocumented
def callable_type(fdef, fallback, ret_type=None): (source)

Undocumented

Parameters
fdef:FuncItemUndocumented
fallback:InstanceUndocumented
ret​_type:Optional[Type]Undocumented
Returns
CallableTypeUndocumented
def class_callable(init_type, info, type_type, special_sig, is_new, orig_self_type=None): (source)
Create a type object type based on the signature of __init__.
Parameters
init​_type:CallableTypeUndocumented
info:TypeInfoUndocumented
type​_type:InstanceUndocumented
special​_sig:Optional[str]Undocumented
is​_new:boolUndocumented
orig​_self​_type:Optional[Type]Undocumented
Returns
CallableTypeUndocumented
def coerce_to_literal(typ): (source)
Recursively converts any Instances that have a last_known_value or are instances of enum types with a single value into the corresponding LiteralType.
Parameters
typ:TypeUndocumented
Returns
TypeUndocumented
def custom_special_method(typ, name, check_all=False): (source)

Does this type have a custom special method such as __format__() or __eq__()?

If check_all is True ensure all items of a union have a custom method, not just some.

Parameters
typ:TypeUndocumented
name:strUndocumented
check​_all:boolUndocumented
Returns
boolUndocumented
def erase_def_to_union_or_bound(tdef): (source)

Undocumented

Parameters
tdef:TypeVarLikeTypeUndocumented
Returns
TypeUndocumented
def erase_to_bound(t): (source)

Undocumented

Parameters
t:TypeUndocumented
Returns
TypeUndocumented
def erase_to_union_or_bound(typ): (source)

Undocumented

Parameters
typ:TypeVarTypeUndocumented
Returns
ProperTypeUndocumented
def false_only(t): (source)
Restricted version of t with only False-ish values
Parameters
t:TypeUndocumented
Returns
ProperTypeUndocumented
def function_type(func, fallback): (source)

Undocumented

Parameters
func:FuncBaseUndocumented
fallback:InstanceUndocumented
Returns
FunctionLikeUndocumented
def get_enum_values(typ): (source)
Return the list of values for an Enum.
Parameters
typ:InstanceUndocumented
Returns
List[str]Undocumented
def get_type_vars(tp): (source)

Undocumented

Parameters
tp:TypeUndocumented
Returns
List[TypeVarType]Undocumented
def is_literal_type_like(t): (source)
Returns 'true' if the given type context is potentially either a LiteralType, a Union of LiteralType, or something similar.
Parameters
t:Optional[Type]Undocumented
Returns
boolUndocumented
def is_recursive_pair(s, t): (source)
Is this a pair of recursive type aliases?
Parameters
s:TypeUndocumented
t:TypeUndocumented
Returns
boolUndocumented
def is_redundant_literal_instance(general, specific): (source)

Undocumented

Parameters
general:ProperTypeUndocumented
specific:ProperTypeUndocumented
Returns
boolUndocumented
def is_simple_literal(t): (source)

Whether a type is a simple enough literal to allow for fast Union simplification

For now this means enum or string

Parameters
t:ProperTypeUndocumented
Returns
boolUndocumented
def is_singleton_type(typ): (source)

Returns 'true' if this type is a "singleton type" -- if there exists exactly only one runtime value associated with this type.

That is, given two values 'a' and 'b' that have the same type 't', 'is_singleton_type(t)' returns True if and only if the expression 'a is b' is always true.

Currently, this returns True when given NoneTypes, enum LiteralTypes and enum types with a single value.

Note that other kinds of LiteralTypes cannot count as singleton types. For example, suppose we do 'a = 100000 + 1' and 'b = 100001'. It is not guaranteed that 'a is b' will always be true -- some implementations of Python will end up constructing two distinct instances of 100001.

Parameters
typ:TypeUndocumented
Returns
boolUndocumented
def make_simplified_union(items, line=-1, column=-1, *, keep_erased=False, contract_literals=True): (source)

Build union type with redundant union items removed.

If only a single item remains, this may return a non-union type.

Examples:

  • [int, str] -> Union[int, str]
  • [int, object] -> object
  • [int, int] -> int
  • [int, Any] -> Union[int, Any] (Any types are not simplified away!)
  • [Any, Any] -> Any
Note: This must NOT be used during semantic analysis, since TypeInfos may not
be fully initialized.

The keep_erased flag is used for type inference against union types containing type variables. If set to True, keep all ErasedType items.

Parameters
items:Sequence[Type]Undocumented
line:intUndocumented
column:intUndocumented
keep​_erased:boolUndocumented
contract​_literals:boolUndocumented
Returns
ProperTypeUndocumented
def map_type_from_supertype(typ, sub_info, super_info): (source)

Map type variables in a type defined in a supertype context to be valid in the subtype context. Assume that the result is unique; if more than one type is possible, return one of the alternatives.

For example, assume

class D(Generic[S]): ... class C(D[E[T]], Generic[T]): ...

Now S in the context of D would be mapped to E[T] in the context of C.

Parameters
typ:TypeUndocumented
sub​_info:TypeInfoUndocumented
super​_info:TypeInfoUndocumented
Returns
TypeUndocumented
def supported_self_type(typ): (source)

Is this a supported kind of explicit self-types?

Currently, this means a X or Type[X], where X is an instance or a type variable with an instance upper bound.

Parameters
typ:ProperTypeUndocumented
Returns
boolUndocumented
def true_only(t): (source)
Restricted version of t with only True-ish values
Parameters
t:TypeUndocumented
Returns
ProperTypeUndocumented
def true_or_false(t): (source)
Unrestricted version of t with both True-ish and False-ish values
Parameters
t:TypeUndocumented
Returns
ProperTypeUndocumented
def try_contracting_literals_in_union(types): (source)

Contracts any literal types back into a sum type if possible.

Will replace the first instance of the literal with the sum type and remove all others.

If we call try_contracting_union(Literal[Color.RED, Color.BLUE, Color.YELLOW]), this function will return Color.

We also treat Literal[True, False] as bool.

Parameters
types:Sequence[Type]Undocumented
Returns
List[ProperType]Undocumented
def try_expanding_sum_type_to_union(typ, target_fullname): (source)

Attempts to recursively expand any enum Instances with the given target_fullname into a Union of all of its component LiteralTypes.

For example, if we have:

class Color(Enum):
RED = 1 BLUE = 2 YELLOW = 3
class Status(Enum):
SUCCESS = 1 FAILURE = 2 UNKNOWN = 3

...and if we call try_expanding_enum_to_union(Union[Color, Status], 'module.Color'), this function will return Literal[Color.RED, Color.BLUE, Color.YELLOW, Status].

Parameters
typ:TypeUndocumented
target​_fullname:strUndocumented
Returns
ProperTypeUndocumented
def try_getting_instance_fallback(typ): (source)

Returns the Instance fallback for this type if one exists.

Otherwise, returns None.

Parameters
typ:ProperTypeUndocumented
Returns
Optional[Instance]Undocumented
def try_getting_int_literals_from_type(typ): (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.

For example, if we had the type 'Literal[1, 2, 3]' as input, this function would return a list of ints [1, 2, 3].

Parameters
typ:TypeUndocumented
Returns
Optional[List[int]]Undocumented
def try_getting_literals_from_type(typ, target_literal_type, target_fullname): (source)
If the given expression or type corresponds to a Literal or union of Literals where the underlying values corresponds to the given target type, returns a list of those underlying values. Otherwise, returns None.
Parameters
typ:TypeUndocumented
target​_literal​_type:TypingType[T]Undocumented
target​_fullname:strUndocumented
Returns
Optional[List[T]]Undocumented
def try_getting_str_literals(expr, typ): (source)

If the given expression or type corresponds to a string literal or a union of string literals, returns a list of the underlying strings. Otherwise, returns None.

Specifically, this function is guaranteed to return a list with one or more strings if one one the following is true:

  1. 'expr' is a StrExpr
  2. 'typ' is a LiteralType containing a string
  3. 'typ' is a UnionType containing only LiteralType of strings
Parameters
expr:ExpressionUndocumented
typ:TypeUndocumented
Returns
Optional[List[str]]Undocumented
def try_getting_str_literals_from_type(typ): (source)

If the given expression or type corresponds to a string Literal or a union of string Literals, returns a list of the underlying strings. Otherwise, returns None.

For example, if we had the type 'Literal["foo", "bar"]' as input, this function would return a list of strings ["foo", "bar"].

Parameters
typ:TypeUndocumented
Returns
Optional[List[str]]Undocumented
def tuple_fallback(typ): (source)
Return fallback type for a tuple.
Parameters
typ:TupleTypeUndocumented
Returns
InstanceUndocumented
def type_object_type_from_function(signature, info, def_info, fallback, is_new): (source)

Undocumented

Parameters
signature:FunctionLikeUndocumented
info:TypeInfoUndocumented
def​_info:TypeInfoUndocumented
fallback:InstanceUndocumented
is​_new:boolUndocumented
Returns
FunctionLikeUndocumented

Undocumented

Value
TypeVar('F',
        bound=FunctionLike)

Undocumented

Value
TypeVar('T')
def _get_type_special_method_bool_ret_type(t): (source)

Undocumented

Parameters
t:TypeUndocumented
Returns
Optional[Type]Undocumented