Skip to content

Commit 838a73b

Browse files
committed
Additional TypeVar defaults validation
1 parent 4e11d1a commit 838a73b

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
@@ -5152,6 +5152,15 @@ def visit_temp_node(self, e: TempNode) -> Type:
51525152
return e.type
51535153

51545154
def visit_type_var_expr(self, e: TypeVarExpr) -> Type:
5155+
p_default = get_proper_type(e.default)
5156+
if not (
5157+
isinstance(p_default, AnyType)
5158+
and p_default.type_of_any == TypeOfAny.from_omitted_generics
5159+
):
5160+
if not is_subtype(p_default, e.upper_bound):
5161+
self.chk.fail("TypeVar default must be a subtype of the bound type", e)
5162+
if e.values and not any(p_default == value for value in e.values):
5163+
self.chk.fail("TypeVar default must be one of the constraint types", e)
51555164
return AnyType(TypeOfAny.special_form)
51565165

51575166
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
@@ -73,6 +73,15 @@ Ts2 = TypeVarTuple("Ts2", default=int) # E: The default argument to TypeVarTupl
7373
Ts3 = TypeVarTuple("Ts3", default=Tuple[int]) # E: The default argument to TypeVarTuple must be an Unpacked tuple
7474
[builtins fixtures/tuple.pyi]
7575

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

0 commit comments

Comments
 (0)