Skip to content
39 changes: 39 additions & 0 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,45 @@ inferred by mypy. This is not valid:
If you really need this, you can define a generic class with a ``__call__``
method.

.. _generic-default-values:

Default values for generic parameters
*************************************

The default value of a parameter whose type contains a type variable doesn't need
to be valid for every possible value of the type variable. Instead, mypy checks the
default value at each call site where the argument is omitted, as if the default
value had been passed explicitly. This means that the default value can also be
used to infer the value of the type variable (Python 3.12 syntax):

.. code-block:: python

class Registry[K, V]:
def get[T](self, key: K, default: T = None) -> V | T:
...

def check(registry: Registry[str, int]) -> None:
reveal_type(registry.get("a")) # Revealed type is "builtins.int | None"
reveal_type(registry.get("a", 0)) # Revealed type is "builtins.int"

Here ``T`` is inferred to be ``None`` if ``default`` is omitted. If the
type variable is already determined in some other way, the default value must
be compatible with it:

.. code-block:: python

class Box[T]:
def put(self, item: T = None) -> None:
...

Box[int]().put(1) # OK
Box[int | None]().put() # OK
Box[int]().put() # Error: Default value for argument "item" to "put" of
# "Box" has incompatible type "None"; expected "int"

Mypy still reports an error in the definition if the default value can never be
valid, for example if it is not compatible with the upper bound of a type variable.

.. _type-variable-upper-bound:

Type variables with upper bounds
Expand Down
11 changes: 10 additions & 1 deletion mypy/applytype.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,15 @@ def apply_generic_arguments(
return callable.copy_modified(variables=[tv for tv in tvars if tv.id not in id_to_type])
else:
callable = callable.copy_modified(
arg_types=[expand_type(at, id_to_type) for at in callable.arg_types]
arg_types=[expand_type(at, id_to_type) for at in callable.arg_types],
default_types=(
[
expand_type(t, id_to_type) if t is not None else None
for t in callable.default_types
]
if callable.default_types is not None
else None
),
)

# Apply arguments to TypeGuard and TypeIs if any.
Expand Down Expand Up @@ -208,6 +216,7 @@ def apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> Calla
arg_types=[t.accept(PolyTranslator(poly_tvars)) for t in tp.arg_types],
ret_type=tp.ret_type.accept(PolyTranslator(poly_tvars)),
variables=[],
default_types=tp.default_types,
)
except PolyTranslationError:
return None
Expand Down
2 changes: 1 addition & 1 deletion mypy/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
from mypy_extensions import u8

# High-level cache layout format
CACHE_VERSION: Final = 12
CACHE_VERSION: Final = 13

# Type used internally to represent errors:
# (path, line, column, end_line, end_column, severity, message, code)
Expand Down
146 changes: 134 additions & 12 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(self) -> None:
)

import mypy.checkexpr
from mypy import errorcodes as codes, join, message_registry, nodes, operators
from mypy import applytype, errorcodes as codes, join, message_registry, nodes, operators
from mypy.binder import ConditionalTypeBinder, Frame, get_declaration
from mypy.checker_shared import CheckerScope, TypeCheckerSharedApi, TypeRange
from mypy.checker_state import checker_state
Expand Down Expand Up @@ -106,6 +106,7 @@ def __init__(self) -> None:
report_internal_error,
)
from mypy.expandtype import expand_type
from mypy.infer import infer_type_arguments
from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash
from mypy.maptype import map_instance_to_supertype
from mypy.meet import is_overlapping_types, meet_types
Expand Down Expand Up @@ -138,6 +139,7 @@ def __init__(self) -> None:
MDEF,
NOT_ABSTRACT,
SYMBOL_FUNCBASE_TYPES,
Argument,
AssertStmt,
AssignmentExpr,
AssignmentStmt,
Expand Down Expand Up @@ -242,6 +244,7 @@ def __init__(self) -> None:
can_have_shared_disjoint_base,
coerce_to_literal,
custom_special_method,
default_call_site_type_vars,
erase_def_to_union_or_bound,
erase_to_bound,
erase_to_union_or_bound,
Expand Down Expand Up @@ -763,6 +766,11 @@ def defer_node(self, node: DeferredNodeType, enclosing_class: TypeInfo | None) -
self.deferred_nodes.append(DeferredNode(node, enclosing_class))

def handle_cannot_determine_type(self, name: str, context: Context) -> None:
if not self.defer_current_node():
self.msg.cannot_determine_type(name, context)

def defer_current_node(self) -> bool:
"""Defer the current function, if possible. Return True if it was deferred."""
node = self.scope.top_level_function()
if self.pass_num < self.last_pass and isinstance(node, FuncDef):
# Don't report an error yet. Just defer. Note that we don't defer
Expand All @@ -775,8 +783,8 @@ def handle_cannot_determine_type(self, name: str, context: Context) -> None:
# function. Any inferred types could be bogus, because there's at
# least one type that we don't know.
self.current_node_deferred = True
else:
self.msg.cannot_determine_type(name, context)
return True
return False

def accept(self, stmt: Statement) -> None:
"""Type check a node in the given type context."""
Expand Down Expand Up @@ -907,8 +915,7 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# Type check initialization expressions.
# TODO: initializers can infer types if they contain a walrus,
# it may be not safe to optimize them away completely.
if not self.can_skip_diagnostics:
self.check_default_params(fdef.func)
self.check_default_params(fdef.func)
if self.recurse_into_functions or fdef.func.def_or_infer_vars:
with (
self.tscope.function_scope(fdef.func),
Expand Down Expand Up @@ -1149,7 +1156,10 @@ def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:
# Prevent extra noise from inconsistent use of @classmethod by copying
# the first arg from the method being checked against.
if sig1.arg_types and defn.info:
impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:])
impl = impl.copy_modified(
arg_types=[sig1.arg_types[0]] + impl.arg_types[1:],
default_types=impl.default_types,
)

# Is the overload alternative's arguments subtypes of the implementation's?
if not is_callable_compatible(
Expand Down Expand Up @@ -1370,8 +1380,7 @@ def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Ty

def visit_func_def(self, defn: FuncDef) -> None:
# Type check initialization expressions as part of top-level.
if not self.can_skip_diagnostics:
self.check_default_params(defn)
self.check_default_params(defn)
if defn.original_def:
# Override previous definition (may affect externally visible types).
new_type = self.function_type(defn)
Expand Down Expand Up @@ -1884,14 +1893,25 @@ def check_unbound_return_typevar(self, typ: CallableType, context: Context) -> N
def check_default_params(self, item: FuncItem, body_is_trivial: bool | None = None) -> None:
if body_is_trivial is None:
body_is_trivial = is_trivial_body(item.body)
typ = item.type
if not isinstance(typ, CallableType) or len(typ.arg_types) != len(item.arguments):
typ = None
default_types: list[Type | None] = [None] * len(item.arguments)
# Although initializers are checked as part of the top-level, we do not
# show errors in them if they appear in an unannotated function.
self.dynamic_funcs.append(item.is_dynamic())
for param in item.arguments:
for i, param in enumerate(item.arguments):
if param.initializer is None:
continue
if body_is_trivial and isinstance(param.initializer, EllipsisExpr):
continue
type_vars = (
default_call_site_type_vars(item, typ, i, body_is_trivial)
if typ is not None
else []
)
if self.can_skip_diagnostics and not type_vars:
continue
name = param.variable.name
msg = "Incompatible default for "
if name.startswith("__tuple_param_"):
Expand All @@ -1911,16 +1931,116 @@ def check_default_params(self, item: FuncItem, body_is_trivial: bool | None = No
]
else:
notes = None
error_msg = ErrorMessage(msg, code=codes.ASSIGNMENT)
if type_vars:
default_types[i] = self.check_generic_default_param(
param, type_vars, error_msg, notes
)
continue
self.check_simple_assignment(
param.variable.type,
param.initializer,
context=param.initializer,
msg=ErrorMessage(msg, code=codes.ASSIGNMENT),
msg=error_msg,
lvalue_name="parameter",
rvalue_name="default",
notes=notes,
)
self.dynamic_funcs.pop()
if typ is not None:
# Record the types of default values that need to be checked at call sites.
# Note that we modify the function type in place, since there may be other
# references to it, and callers may have to wait for this (see
# ExpressionChecker.wait_for_default_types()).
typ.set_default_types(default_types)
if isinstance(item, FuncDef):
item.default_types_pending = False

def check_generic_default_param(
self,
param: Argument,
type_vars: list[TypeVarLikeType],
msg: ErrorMessage,
notes: list[str] | None,
) -> Type | None:
"""Check default value of a parameter whose declared type has type variables.

The default value doesn't need to match the declared type for all values of
the given type variables (see default_call_site_type_vars()), since it is
checked at call sites instead (see CallableType.default_types). We only give
an error here if it can never match, e.g. because of an upper bound.

Return the type of the default value if it needs to be checked at call sites.
"""
assert param.initializer is not None and param.variable.type is not None
declared_type = param.variable.type
# First try the declared type as context, as for regular defaults.
with self.msg.filter_errors() as watcher:
default_type = self.expr_checker.accept(
param.initializer, type_context=declared_type, always_allow_any=True
)
if not watcher.has_new_errors() and is_subtype(
default_type, declared_type, options=self.options
):
return None
# Otherwise infer without the context (e.g. the context T gives errors for [1]).
with self.msg.filter_errors(save_filtered_errors=True) as watcher:
default_type = self.expr_checker.accept(param.initializer)
if is_subtype(default_type, declared_type, options=self.options) or has_any_type(
default_type
):
# The type is less precise without the context (e.g. a lambda gets Any
# parameters), so we can't rely on it. Check it like a regular default.
if not self.can_skip_diagnostics:
self.check_simple_assignment(
declared_type,
param.initializer,
context=param.initializer,
msg=msg,
lvalue_name="parameter",
rvalue_name="default",
notes=notes,
)
return None
if not self.can_skip_diagnostics:
# Report only errors not caused by the context.
self.msg.add_errors(watcher.filtered_errors())
if not self.can_be_subtype_of_generic(default_type, declared_type, type_vars):
if not self.can_skip_diagnostics:
self.check_subtype(
default_type,
declared_type,
param.initializer,
msg,
"default has type",
"parameter has type",
notes=notes,
)
return None
return default_type

def can_be_subtype_of_generic(
self, typ: Type, generic: Type, type_vars: list[TypeVarLikeType]
) -> bool:
"""Is typ a subtype of generic for some values of the given type variables?"""
args, _ = infer_type_arguments(type_vars, generic, typ, is_supertype=True)
failed = False

def report(*args: object) -> None:
nonlocal failed
failed = True

# Use a dummy callable to check type variable bounds and values.
dummy = CallableType(
[generic],
[ARG_POS],
[None],
AnyType(TypeOfAny.special_form),
self.named_type("builtins.function"),
variables=type_vars,
)
applied = applytype.apply_generic_arguments(dummy, args, report, context=dummy)
return not failed and is_subtype(typ, applied.arg_types[0], options=self.options)

def is_forward_op_method(self, method_name: str) -> bool:
return method_name in operators.reverse_op_methods
Expand Down Expand Up @@ -2045,6 +2165,7 @@ def check_reverse_op_method(
arg_types=[reverse_type.arg_types[0]] * 2,
arg_kinds=[ARG_POS] * 2,
arg_names=[reverse_type.arg_names[0], "_"],
default_types=None,
)
assert len(reverse_type.arg_types) >= 2

Expand Down Expand Up @@ -2182,11 +2303,13 @@ def is_unsafe_overlapping_op(
arg_types=[forward_base_erased, forward_item.arg_types[0]],
arg_kinds=[nodes.ARG_POS] * 2,
arg_names=[None] * 2,
default_types=None,
)
reverse_tweaked = reverse_type.copy_modified(
arg_types=[reverse_type.arg_types[1], reverse_type.arg_types[0]],
arg_kinds=[nodes.ARG_POS] * 2,
arg_names=[None] * 2,
default_types=None,
)

reverse_base_erased = reverse_type.arg_types[0]
Expand Down Expand Up @@ -5916,8 +6039,7 @@ def visit_decorator_inner(
defn.type = typ.copy_modified(ret_type=ret_type)

# Type check initialization expressions as part of top-level.
if not self.can_skip_diagnostics:
self.check_default_params(defn)
self.check_default_params(defn)

if self.recurse_into_functions or e.func.def_or_infer_vars:
with self.tscope.function_scope(e.func), self.set_recurse_into_functions():
Expand Down
Loading
Loading