diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 2b37d10e2aff..530793730f35 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -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, @@ -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 diff --git a/test-data/unit/check-typevar-defaults.test b/test-data/unit/check-typevar-defaults.test index 6136746cbd0a..75453a3a4f80 100644 --- a/test-data/unit/check-typevar-defaults.test +++ b/test-data/unit/check-typevar-defaults.test @@ -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]): ... @@ -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