Skip to content

Commit 3f58c2d

Browse files
authored
Fix TypeVar defaults with None (PEP 696) (#16859)
Ref: #14851
1 parent 67c3969 commit 3f58c2d

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

Diff for: mypy/typeanal.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
from mypy.options import Options
4040
from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface
4141
from mypy.semanal_shared import SemanticAnalyzerCoreInterface, paramspec_args, paramspec_kwargs
42+
from mypy.state import state
4243
from mypy.tvar_scope import TypeVarLikeScope
4344
from mypy.types import (
4445
ANNOTATED_TYPE_NAMES,
@@ -1893,7 +1894,8 @@ def fix_instance(
18931894
t.args = tuple(args)
18941895
fix_type_var_tuple_argument(t)
18951896
if not t.type.has_type_var_tuple_type:
1896-
fixed = expand_type(t, env)
1897+
with state.strict_optional_set(options.strict_optional):
1898+
fixed = expand_type(t, env)
18971899
assert isinstance(fixed, Instance)
18981900
t.args = fixed.args
18991901

Diff for: test-data/unit/check-typevar-defaults.test

+15
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ from typing import Generic, TypeVar, Union, overload
124124
T1 = TypeVar("T1")
125125
T2 = TypeVar("T2", default=int)
126126
T3 = TypeVar("T3", default=str)
127+
T4 = TypeVar("T4", default=Union[int, None])
127128

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

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

204+
class ClassA4(Generic[T4]): ...
205+
206+
def func_a4(
207+
a: ClassA4,
208+
b: ClassA4[float],
209+
) -> None:
210+
reveal_type(a) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
211+
reveal_type(b) # N: Revealed type is "__main__.ClassA4[builtins.float]"
212+
213+
k = ClassA4()
214+
reveal_type(k) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
215+
l = ClassA4[float]()
216+
reveal_type(l) # N: Revealed type is "__main__.ClassA4[builtins.float]"
217+
203218
[case testTypeVarDefaultsClass2]
204219
# flags: --disallow-any-generics
205220
from typing import Generic, ParamSpec

0 commit comments

Comments
 (0)