Skip to content

Commit 982aca1

Browse files
committed
Additional TypeVar defaults validation
1 parent f38d409 commit 982aca1

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

mypy/checkexpr.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5140,6 +5140,15 @@ def visit_temp_node(self, e: TempNode) -> Type:
51405140
return e.type
51415141

51425142
def visit_type_var_expr(self, e: TypeVarExpr) -> Type:
5143+
p_default = get_proper_type(e.default)
5144+
if not (
5145+
isinstance(p_default, AnyType)
5146+
and p_default.type_of_any == TypeOfAny.from_omitted_generics
5147+
):
5148+
if not is_subtype(p_default, e.upper_bound):
5149+
self.chk.fail("TypeVar default must be a subtype of the bound type", e)
5150+
if e.values and not any(p_default == value for value in e.values):
5151+
self.chk.fail("TypeVar default must be one of the constraint types", e)
51435152
return AnyType(TypeOfAny.special_form)
51445153

51455154
def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type:

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ Ts2 = TypeVarTuple("Ts2", default=int) # E: The default argument to TypeVarTupl
7272
Ts3 = TypeVarTuple("Ts3", default=Tuple[int]) # E: The default argument to TypeVarTuple must be an Unpacked tuple
7373
[builtins fixtures/tuple.pyi]
7474

75+
[case testTypeVarDefaultsInvalid2]
76+
from typing import TypeVar, List, Union
77+
78+
T1 = TypeVar("T1", bound=str, default=int) # E: TypeVar default must be a subtype of the bound type
79+
T2 = TypeVar("T2", bound=List[str], default=List[int]) # E: TypeVar default must be a subtype of the bound type
80+
T3 = TypeVar("T3", int, str, default=bytes) # E: TypeVar default must be one of the constraint types
81+
T4 = TypeVar("T4", int, str, default=Union[int, str]) # E: TypeVar default must be one of the constraint types
82+
T5 = TypeVar("T5", float, str, default=int) # E: TypeVar default must be one of the constraint types
83+
7584
[case testTypeVarDefaultsFunctions]
7685
from typing import TypeVar, ParamSpec, List, Union, Callable, Tuple
7786
from typing_extensions import TypeVarTuple, Unpack

0 commit comments

Comments
 (0)