Skip to content

Fix TypeVar defaults with None (PEP 696) #16859

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from mypy.options import Options
from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface
from mypy.semanal_shared import SemanticAnalyzerCoreInterface, paramspec_args, paramspec_kwargs
from mypy.state import state
from mypy.tvar_scope import TypeVarLikeScope
from mypy.types import (
ANNOTATED_TYPE_NAMES,
Expand Down Expand Up @@ -1893,7 +1894,8 @@ def fix_instance(
t.args = tuple(args)
fix_type_var_tuple_argument(t)
if not t.type.has_type_var_tuple_type:
fixed = expand_type(t, env)
with state.strict_optional_set(options.strict_optional):
fixed = expand_type(t, env)
assert isinstance(fixed, Instance)
t.args = fixed.args

Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-typevar-defaults.test
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ from typing import Generic, TypeVar, Union, overload
T1 = TypeVar("T1")
T2 = TypeVar("T2", default=int)
T3 = TypeVar("T3", default=str)
T4 = TypeVar("T4", default=Union[int, None])

class ClassA1(Generic[T2, T3]): ...

Expand Down Expand Up @@ -200,6 +201,20 @@ def func_a3(
n = ClassA3[float, float, float]() # E: Type application has too many types (expected between 1 and 2)
reveal_type(n) # N: Revealed type is "Any"

class ClassA4(Generic[T4]): ...

def func_a4(
a: ClassA4,
b: ClassA4[float],
) -> None:
reveal_type(a) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
reveal_type(b) # N: Revealed type is "__main__.ClassA4[builtins.float]"

k = ClassA4()
reveal_type(k) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
l = ClassA4[float]()
reveal_type(l) # N: Revealed type is "__main__.ClassA4[builtins.float]"

[case testTypeVarDefaultsClass2]
# flags: --disallow-any-generics
from typing import Generic, ParamSpec
Expand Down