Skip to content

Commit 013d14e

Browse files
committed
Fix TypeVar defaults with None (PEP 696)
1 parent 1b69a7a commit 013d14e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

mypy/typeanal.py

Lines changed: 3 additions & 1 deletion
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

test-data/unit/check-typevar-defaults.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ from typing import Generic, TypeVar, Union, overload
132132
T1 = TypeVar("T1")
133133
T2 = TypeVar("T2", default=int)
134134
T3 = TypeVar("T3", default=str)
135+
T4 = TypeVar("T4", default=Union[int, None])
135136

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

@@ -208,6 +209,20 @@ def func_a3(
208209
n = ClassA3[float, float, float]() # E: Type application has too many types (expected between 1 and 2)
209210
reveal_type(n) # N: Revealed type is "Any"
210211

212+
class ClassA4(Generic[T4]): ...
213+
214+
def func_a4(
215+
a: ClassA4,
216+
b: ClassA4[float],
217+
) -> None:
218+
reveal_type(a) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
219+
reveal_type(b) # N: Revealed type is "__main__.ClassA4[builtins.float]"
220+
221+
k = ClassA4()
222+
reveal_type(k) # N: Revealed type is "__main__.ClassA4[Union[builtins.int, None]]"
223+
l = ClassA4[float]()
224+
reveal_type(l) # N: Revealed type is "__main__.ClassA4[builtins.float]"
225+
211226
[case testTypeVarDefaultsClass2]
212227
# flags: --disallow-any-generics
213228
from typing import Generic, ParamSpec

0 commit comments

Comments
 (0)