Skip to content

Allow default values for parameters typed with type variables - #22591

Open
andersk wants to merge 9 commits into
python:masterfrom
andersk:generic-default
Open

andersk wants to merge 9 commits into
python:masterfrom
andersk:generic-default

Conversation

@andersk

@andersk andersk commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

A default value for a parameter whose declared type contains type variables no longer has to be valid for every value of those type variables. If it isn’t, it is checked at each call site that omits the argument, as if it had been passed explicitly, so it also takes part in inference:

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

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

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

Box[int | None]().put()  # OK
Box[int]().put()         # error: Default value for argument "item" to "put" of "Box"
                         # has incompatible type "None"; expected "int"
  • Defaults that already match for all values (x: T | None = None, xs: list[T] = []) are handled as before.
  • A default that can never match (e.g. it violates the upper bound) is still an error at the definition. So is one whose type isn’t precise without the declared type as context, such as a lambda with parameters.
  • The default also counts when the function is used as a callable: def f(x: T = 1) -> T is compatible with Callable[[], int] but not Callable[[], str], and an override can’t change such a default to an incompatible type.

This follows the plan outlined by JukkaL and extended by ilevkivskyi: the default’s type is stored in the callable type (a new CallableType.default_types, set only where needed), generates extra constraints when the argument is omitted, and is taken into account by subtyping, join and meet. One difference: instead of inferring such signatures lazily like decorated functions, the signature stays available from semantic analysis and the default types are filled in when the definition is checked; only calls that omit a possibly affected argument wait for them. We can’t tell that a default is fine before checking it, so making every reference wait would defer existing code that uses functions like def f(xs: Sequence[T] = ()), and reject it at the top level of an import cycle.

The series is meant to be read commit by commit.

Things reviewers may want to weigh in on:

  • Existing # type: ignored definitions. def __init__(self, v: T = None) # type: ignore[assignment] is now accepted, so the ignore becomes unused and the check moves to callers: Box[int]() is now an error, including for third-party classes. With a sentinel default, m.get() changes from V to V | Sentinel. I expect mypy_primer to show some of this.
  • Plugins. copy_modified now requires default_types whenever the arguments change, enforced by overloads. Existing plugins keep working at runtime (the list is dropped), but ones type checked against mypy need to provide it.
  • = ... in stubs and protocols. As before, a literal ... default in a stub or other trivial body isn’t treated as a value, so def get(self, default: T = ...) -> T: ... records nothing and get() leaves T unsolved. A stub that wants the new behaviour has to give the actual default, which makes it a different type: an override with default: T = 0 is incompatible with a base that declares default: T = ....
  • Callers checked before the definition. Function bodies are checked after all module top levels, so this only affects top-level code and methods checked with it (e.g. an __init__ that infers attributes). Such a method is deferred if a call in it omits an argument that might need the check. Top-level code in an import cycle can’t be deferred and reports Cannot determine type of "f"; the alternative is to skip the check silently. Passing the function as a value there (rather than calling it) doesn’t wait.
  • Limitation. We record the default’s type, not its expression, so with x: list[T] = [1] on C[T], C[float]().m() is an error although C[float]().m([1]) is fine.

Developed with LLM assistance (Claude Code).

andersk and others added 2 commits December 2, 2026 14:45
Instead of skipping the call to check_default_params when diagnostics
can be skipped, skip checking each default value inside it. This is in
preparation for checking some default values even when diagnostics can
be skipped, since their types will be needed by callers.

This also skips checking default values of lambdas when diagnostics can
be skipped, consistent with functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
with_normalized_var_args only needs to replace *args with other
arguments, so give it a dedicated hook instead of requiring a generic
copy_modified with a common signature. This will allow
CallableType.copy_modified to require extra information when the
arguments change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
@github-actions

This comment has been minimized.

andersk and others added 7 commits December 2, 2026 16:01
This new attribute will record the types of default values that need to
be checked at call sites, because the declared type of the parameter
contains type variables and the default value doesn't match it for all
of their values (python#3737). Nothing sets it yet.

It is expanded, serialized (bumping the cache version), fixed up,
included in fine-grained snapshots, part of equality, and combined by
join and meet. Type queries don't visit it.

Since it is aligned with the arguments, copy_modified requires it to be
passed explicitly whenever the arguments change. Overloads enforce this
statically, so each caller decides whether to keep it, realign it (e.g.
bind_self, functools.partial) or drop it. At runtime, it is dropped for
third-party plugins that don't pass it yet.

It is declared in ParametersBase, but Parameters doesn't record it yet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
If a call omits an argument whose default value type is recorded in
CallableType.default_types, treat the default value as if it was passed
explicitly: use it to infer type variables, and check it against the
declared type after inference. For example, given "def put(self, x: T =
1)" in a generic class C, "C[int]().put()" is fine but "C[str]().put()"
is an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
When a callable with recorded default value types (see
CallableType.default_types) is used as another callable that omits the
corresponding arguments, the default values act as if they were passed
explicitly. Take them into account in is_callable_compatible,
unify_generic_callable, and constraint inference, so that e.g.
"def f(x: T = 1) -> T" is not compatible with Callable[[], str].

If the other callable also records a default value type for the
argument, ours must be a subtype of it instead; e.g. an override can't
replace "default: T = 0" with "default: T = 'x'". Callable[..., X] is
not restricted, since we don't know which arguments are omitted.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
Fixes python#3737.

Previously, a default value for a parameter whose declared type
contains type variables had to be valid for all possible values of the
type variables, so e.g. this was rejected:

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

Now, if the default value doesn't match such a declared type, we
record its type in CallableType.default_types instead of reporting an
error, so that it is checked at each call site that omits the argument
(where it is used to infer T = None above), and when the function is
used as a callable. This applies to type variables of the function
itself, and for a method, those of the enclosing class. We still report
an error at the definition if the default value can never be valid,
e.g. if it doesn't match the upper bound of a type variable, or if its
type isn't precise without the declared type as context, e.g. a lambda
with parameters.

ParamSpec and callers checked before the definition are handled in the
following commits.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
Record default_types in Parameters too, so that a ParamSpec captures
them along with the arguments. For example, a method decorated with a
Callable[P, T] -> Callable[P, T] decorator is still checked at call
sites that omit an argument.

Since the ParamSpec captures them, don't use the default values when
matching against a callable that still has a ParamSpec. Otherwise they
would be used to infer the type variables of a decorated generic
function, so that "def f(x: T = None) -> T" would no longer be generic.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
This will be used to defer a function for other reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
Default value types (see CallableType.default_types) are only recorded
when the function definition is type checked. Most function bodies are
checked after that, but top-level code and methods that infer
attributes (e.g. __init__) may be checked earlier. Defer such a method
if it omits an argument that might need a call site check;
"x: T | None = None" never does. Top-level code can't be deferred
(this matters in import cycles), so it gets a "Cannot determine type"
error instead of silently skipping the check.

This is tracked by FuncDef.default_types_pending, which is set by
semantic analysis and cleared by the type checker, so it is never set
for deserialized or plugin-generated functions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

prefect (https://github.com/PrefectHQ/prefect)
- src/prefect/utilities/collections.py:186: error: Incompatible default for parameter "types" (default has type "type[object]", parameter has type "type[T] | tuple[type[T], ...]")  [assignment]

steam.py (https://github.com/Gobot1234/steam.py)
- steam/tag.py:35: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/tag.py:35: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/tag.py:35: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/tag.py:77: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/tag.py:77: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/tag.py:77: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/tag.py:99: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/tag.py:99: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/tag.py:99: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/app.py:102: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/app.py:102: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/app.py:102: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/app.py:651: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/app.py:651: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/app.py:651: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/package.py:55: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/package.py:55: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/package.py:55: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/package.py:75: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/package.py:75: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/package.py:75: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
- steam/clan.py:211: error: Incompatible default for parameter "type" (default has type "int", parameter has type "BoringEventT")  [assignment]
- steam/bundle.py:36: error: Incompatible default for parameter "name" (default has type "None", parameter has type "NameT")  [assignment]
- steam/bundle.py:36: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
- steam/bundle.py:36: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase

setuptools (https://github.com/pypa/setuptools)
+ setuptools/_reqs.py:38: error: Unused "type: ignore" comment  [unused-ignore]

xarray-dataclasses (https://github.com/astropenguin/xarray-dataclasses)
- xarray_dataclasses/dataarray.py:54: error: Argument 1 to "DataOptions" has incompatible type "type[DataArray]"; expected "Callable[..., TDataArray]"  [arg-type]
- xarray_dataclasses/dataset.py:54: error: Argument 1 to "DataOptions" has incompatible type "type[Dataset]"; expected "Callable[..., TDataset]"  [arg-type]

hydra-zen (https://github.com/mit-ll-responsible-ai/hydra-zen)
- src/hydra_zen/structured_configs/_make_custom_builds.py:65: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:83: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:101: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:119: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:137: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:155: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- src/hydra_zen/structured_configs/_make_custom_builds.py:175: error: Incompatible default for parameter "builds_fn" (default has type "type[DefaultBuilds]", parameter has type "BuildsFn[T] | type[BuildsFn[T]]")  [assignment]
- tests/annotations/declarations.py:929: error: Expression is of type "StdBuilds[Never]", not "StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:934: error: Expression is of type "StdBuilds[Never]", not "StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:940: error: Expression is of type "PBuilds[Never]", not "PBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:944: error: Expression is of type "PBuilds[Never]", not "PBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:945: error: Expression is of type "PBuilds[Never]", not "PBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:951: error: Expression is of type "FullBuilds[Never] | StdBuilds[Never]", not "FullBuilds[SupportedPrimitive] | StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:956: error: Expression is of type "PBuilds[Never] | StdBuilds[Never]", not "PBuilds[SupportedPrimitive] | StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:961: error: Expression is of type "PBuilds[Never] | StdBuilds[Never]", not "PBuilds[SupportedPrimitive] | StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:969: error: Expression is of type "FullBuilds[Never] | PBuilds[Never] | StdBuilds[Never]", not "FullBuilds[SupportedPrimitive] | PBuilds[SupportedPrimitive] | StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:980: error: Expression is of type "FullBuilds[Never] | PBuilds[Never] | StdBuilds[Never]", not "FullBuilds[SupportedPrimitive] | PBuilds[SupportedPrimitive] | StdBuilds[SupportedPrimitive]"  [assert-type]
- tests/annotations/declarations.py:1240: error: Need type annotation for "bf"  [var-annotated]

comtypes (https://github.com/enthought/comtypes)
- comtypes/typeinfo.py:411: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/_post_coinit/misc.py:157: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/client/_create.py:35: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/client/_create.py:78: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/client/_activeobj.py:30: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/server/__init__.py:38: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/git.py:40: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]
- comtypes/git.py:47: error: Incompatible default for parameter "interface" (default has type "type[IUnknown]", parameter has type "type[_T_IUnknown]")  [assignment]

discord.py (https://github.com/Rapptz/discord.py)
- discord/backoff.py:63: error: Incompatible default for parameter "integral" (default has type "Literal[False]", parameter has type "T")  [assignment]
- discord/abc.py:2091: error: Incompatible default for parameter "cls" (default has type "type[VoiceClient]", parameter has type "Callable[[Client, Connectable], T]")  [assignment]

pydantic (https://github.com/pydantic/pydantic)
+ pydantic/root_model.py:61: error: Unused "type: ignore" comment  [unused-ignore]

werkzeug (https://github.com/pallets/werkzeug)
+ src/werkzeug/datastructures/structures.py:816: error: Unused "type: ignore" comment  [unused-ignore]
+ src/werkzeug/datastructures/headers.py:300: error: Unused "type: ignore" comment  [unused-ignore]

mkosi (https://github.com/systemd/mkosi)
+ mkosi/config.py:1257: error: Unused "type: ignore" comment  [unused-ignore]

pandas (https://github.com/pandas-dev/pandas)
+ pandas/core/methods/to_dict.py:107: error: Unused "type: ignore" comment  [unused-ignore]
+ pandas/core/series.py:1981: error: Unused "type: ignore" comment  [unused-ignore]
+ pandas/core/frame.py:1952: error: Unused "type: ignore" comment  [unused-ignore]

jinja (https://github.com/pallets/jinja)
+ src/jinja2/filters.py:548: error: Unused "type: ignore" comment  [unused-ignore]
+ src/jinja2/filters.py:1313: error: Unused "type: ignore" comment  [unused-ignore]
+ src/jinja2/filters.py:1340: error: Unused "type: ignore" comment  [unused-ignore]

meson (https://github.com/mesonbuild/meson)
+ mesonbuild/interpreter/interpreter.py:2470: error: Unused "type: ignore" comment  [unused-ignore]

scikit-build-core (https://github.com/scikit-build/scikit-build-core)
+ src/scikit_build_core/setuptools/wrapper.py:49: error: Unused "type: ignore" comment  [unused-ignore]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unable to specify a default value for a generic parameter

1 participant