Skip to content

Commit

Permalink
Fix TypeVar defaults with None (PEP 696) (#16859)
Browse files Browse the repository at this point in the history
Ref: #14851
  • Loading branch information
cdce8p committed Feb 2, 2024
1 parent 67c3969 commit 3f58c2d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
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

0 comments on commit 3f58c2d

Please sign in to comment.