Skip to content

Commit 10da8e7

Browse files
committed
Add basic TypeVar defaults validation
1 parent c3cc492 commit 10da8e7

8 files changed

+257
-46
lines changed

mypy/exprtotype.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
Type,
3434
TypeList,
3535
TypeOfAny,
36+
TypeOfTypeList,
3637
UnboundType,
3738
UnionType,
3839
)
@@ -161,9 +162,12 @@ def expr_to_unanalyzed_type(
161162
else:
162163
raise TypeTranslationError()
163164
return CallableArgument(typ, name, arg_const, expr.line, expr.column)
164-
elif isinstance(expr, ListExpr):
165+
elif isinstance(expr, (ListExpr, TupleExpr)):
165166
return TypeList(
166167
[expr_to_unanalyzed_type(t, options, allow_new_syntax, expr) for t in expr.items],
168+
TypeOfTypeList.callable_args
169+
if isinstance(expr, ListExpr)
170+
else TypeOfTypeList.param_spec_defaults,
167171
line=expr.line,
168172
column=expr.column,
169173
)

mypy/message_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
179179
INVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of "{}" must be a subtype of {}'
180180
INVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for "{}"'
181181
TYPEVAR_VARIANCE_DEF: Final = 'TypeVar "{}" may only be a literal bool'
182-
TYPEVAR_BOUND_MUST_BE_TYPE: Final = 'TypeVar "bound" must be a type'
182+
TYPEVAR_ARG_MUST_BE_TYPE: Final = '{} "{}" must be a type'
183183
TYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to "TypeVar()"'
184184
UNBOUND_TYPEVAR: Final = (
185185
"A function returning TypeVar should receive at least "

mypy/semanal.py

Lines changed: 123 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4096,28 +4096,17 @@ def process_typevar_parameters(
40964096
if has_values:
40974097
self.fail("TypeVar cannot have both values and an upper bound", context)
40984098
return None
4099-
try:
4100-
# We want to use our custom error message below, so we suppress
4101-
# the default error message for invalid types here.
4102-
analyzed = self.expr_to_analyzed_type(
4103-
param_value, allow_placeholder=True, report_invalid_types=False
4104-
)
4105-
if analyzed is None:
4106-
# Type variables are special: we need to place them in the symbol table
4107-
# soon, even if upper bound is not ready yet. Otherwise avoiding
4108-
# a "deadlock" in this common pattern would be tricky:
4109-
# T = TypeVar('T', bound=Custom[Any])
4110-
# class Custom(Generic[T]):
4111-
# ...
4112-
analyzed = PlaceholderType(None, [], context.line)
4113-
upper_bound = get_proper_type(analyzed)
4114-
if isinstance(upper_bound, AnyType) and upper_bound.is_from_error:
4115-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4116-
# Note: we do not return 'None' here -- we want to continue
4117-
# using the AnyType as the upper bound.
4118-
except TypeTranslationError:
4119-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4099+
tv_arg = self.get_typevarlike_argument("TypeVar", param_name, param_value, context)
4100+
if tv_arg is None:
41204101
return None
4102+
upper_bound = tv_arg
4103+
elif param_name == "default":
4104+
tv_arg = self.get_typevarlike_argument(
4105+
"TypeVar", param_name, param_value, context, allow_unbound_tvars=True
4106+
)
4107+
if tv_arg is None:
4108+
return None
4109+
default = tv_arg
41214110
elif param_name == "values":
41224111
# Probably using obsolete syntax with values=(...). Explain the current syntax.
41234112
self.fail('TypeVar "values" argument not supported', context)
@@ -4145,6 +4134,50 @@ def process_typevar_parameters(
41454134
variance = INVARIANT
41464135
return variance, upper_bound, default
41474136

4137+
def get_typevarlike_argument(
4138+
self,
4139+
typevarlike_name: str,
4140+
param_name: str,
4141+
param_value: Expression,
4142+
context: Context,
4143+
*,
4144+
allow_unbound_tvars: bool = False,
4145+
allow_param_spec_literals: bool = False,
4146+
) -> ProperType | None:
4147+
try:
4148+
# We want to use our custom error message below, so we suppress
4149+
# the default error message for invalid types here.
4150+
analyzed = self.expr_to_analyzed_type(
4151+
param_value,
4152+
allow_placeholder=True,
4153+
report_invalid_types=False,
4154+
allow_unbound_tvars=allow_unbound_tvars,
4155+
allow_param_spec_literals=allow_param_spec_literals,
4156+
)
4157+
if analyzed is None:
4158+
# Type variables are special: we need to place them in the symbol table
4159+
# soon, even if upper bound is not ready yet. Otherwise avoiding
4160+
# a "deadlock" in this common pattern would be tricky:
4161+
# T = TypeVar('T', bound=Custom[Any])
4162+
# class Custom(Generic[T]):
4163+
# ...
4164+
analyzed = PlaceholderType(None, [], context.line)
4165+
typ = get_proper_type(analyzed)
4166+
if isinstance(typ, AnyType) and typ.is_from_error:
4167+
self.fail(
4168+
message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),
4169+
param_value,
4170+
)
4171+
# Note: we do not return 'None' here -- we want to continue
4172+
# using the AnyType as the upper bound.
4173+
return typ
4174+
except TypeTranslationError:
4175+
self.fail(
4176+
message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),
4177+
param_value,
4178+
)
4179+
return None
4180+
41484181
def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str | None:
41494182
if not call:
41504183
return None
@@ -4177,13 +4210,47 @@ def process_paramspec_declaration(self, s: AssignmentStmt) -> bool:
41774210
if name is None:
41784211
return False
41794212

4180-
# ParamSpec is different from a regular TypeVar:
4181-
# arguments are not semantically valid. But, allowed in runtime.
4182-
# So, we need to warn users about possible invalid usage.
4183-
if len(call.args) > 1:
4184-
self.fail("Only the first argument to ParamSpec has defined semantics", s)
4213+
n_values = call.arg_kinds[1:].count(ARG_POS)
4214+
if n_values != 0:
4215+
self.fail("Only the first positional argument to ParamSpec has defined semantics", s)
41854216

41864217
default: Type = AnyType(TypeOfAny.from_omitted_generics)
4218+
for param_value, param_name in zip(
4219+
call.args[1 + n_values :], call.arg_names[1 + n_values :]
4220+
):
4221+
if param_name == "default":
4222+
tv_arg = self.get_typevarlike_argument(
4223+
"ParamSpec",
4224+
param_name,
4225+
param_value,
4226+
s,
4227+
allow_unbound_tvars=True,
4228+
allow_param_spec_literals=True,
4229+
)
4230+
if tv_arg is None:
4231+
return False
4232+
default = tv_arg
4233+
if isinstance(tv_arg, Parameters):
4234+
for i, arg_type in enumerate(tv_arg.arg_types):
4235+
typ = get_proper_type(arg_type)
4236+
if isinstance(typ, AnyType) and typ.is_from_error:
4237+
self.fail(
4238+
f"Argument {i} of ParamSpec default must be a type", param_value
4239+
)
4240+
elif not isinstance(default, (AnyType, UnboundType)):
4241+
self.fail(
4242+
"The default argument to ParamSpec must be a tuple expression, ellipsis, or a ParamSpec",
4243+
param_value,
4244+
)
4245+
default = AnyType(TypeOfAny.from_error)
4246+
else:
4247+
# ParamSpec is different from a regular TypeVar:
4248+
# arguments are not semantically valid. But, allowed in runtime.
4249+
# So, we need to warn users about possible invalid usage.
4250+
self.fail(
4251+
"The variance and bound arguments to ParamSpec do not have defined semantics yet",
4252+
s,
4253+
)
41874254

41884255
# PEP 612 reserves the right to define bound, covariant and contravariant arguments to
41894256
# ParamSpec in a later PEP. If and when that happens, we should do something
@@ -4211,10 +4278,34 @@ def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool:
42114278
if not call:
42124279
return False
42134280

4214-
if len(call.args) > 1:
4215-
self.fail("Only the first argument to TypeVarTuple has defined semantics", s)
4281+
n_values = call.arg_kinds[1:].count(ARG_POS)
4282+
if n_values != 0:
4283+
self.fail(
4284+
"Only the first positional argument to TypeVarTuple has defined semantics", s
4285+
)
42164286

42174287
default: Type = AnyType(TypeOfAny.from_omitted_generics)
4288+
for param_value, param_name in zip(
4289+
call.args[1 + n_values :], call.arg_names[1 + n_values :]
4290+
):
4291+
if param_name == "default":
4292+
tv_arg = self.get_typevarlike_argument(
4293+
"TypeVarTuple", param_name, param_value, s, allow_unbound_tvars=True
4294+
)
4295+
if tv_arg is None:
4296+
return False
4297+
default = tv_arg
4298+
if not isinstance(default, UnpackType):
4299+
self.fail(
4300+
"The default argument to TypeVarTuple must be an Unpacked tuple",
4301+
param_value,
4302+
)
4303+
default = AnyType(TypeOfAny.from_error)
4304+
else:
4305+
self.fail(
4306+
"The variance and bound arguments to TypeVarTuple do not have defined semantics yet",
4307+
s,
4308+
)
42184309

42194310
if not self.incomplete_feature_enabled(TYPE_VAR_TUPLE, s):
42204311
return False
@@ -6308,6 +6399,8 @@ def expr_to_analyzed_type(
63086399
report_invalid_types: bool = True,
63096400
allow_placeholder: bool = False,
63106401
allow_type_any: bool = False,
6402+
allow_unbound_tvars: bool = False,
6403+
allow_param_spec_literals: bool = False,
63116404
) -> Type | None:
63126405
if isinstance(expr, CallExpr):
63136406
# This is a legacy syntax intended mostly for Python 2, we keep it for
@@ -6336,6 +6429,8 @@ def expr_to_analyzed_type(
63366429
report_invalid_types=report_invalid_types,
63376430
allow_placeholder=allow_placeholder,
63386431
allow_type_any=allow_type_any,
6432+
allow_unbound_tvars=allow_unbound_tvars,
6433+
allow_param_spec_literals=allow_param_spec_literals,
63396434
)
63406435

63416436
def analyze_type_expr(self, expr: Expression) -> None:

mypy/typeanal.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
TypedDictType,
7373
TypeList,
7474
TypeOfAny,
75+
TypeOfTypeList,
7576
TypeQuery,
7677
TypeType,
7778
TypeVarLikeType,
@@ -890,10 +891,12 @@ def visit_type_list(self, t: TypeList) -> Type:
890891
else:
891892
return AnyType(TypeOfAny.from_error)
892893
else:
894+
s = "[...]" if t.list_type == TypeOfTypeList.callable_args else "(...)"
893895
self.fail(
894-
'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE
896+
f'Bracketed expression "{s}" is not valid as a type', t, code=codes.VALID_TYPE
895897
)
896-
self.note('Did you mean "List[...]"?', t)
898+
if t.list_type == TypeOfTypeList.callable_args:
899+
self.note('Did you mean "List[...]"?', t)
897900
return AnyType(TypeOfAny.from_error)
898901

899902
def visit_callable_argument(self, t: CallableArgument) -> Type:

mypy/types.py

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,17 @@ class TypeOfAny:
196196
suggestion_engine: Final = 9
197197

198198

199+
class TypeOfTypeList:
200+
"""This class describes the different types of TypeList."""
201+
202+
__slots__ = ()
203+
204+
# List expressions for callable args
205+
callable_args: Final = 1
206+
# Tuple expressions for ParamSpec defaults
207+
param_spec_defaults: Final = 2
208+
209+
199210
def deserialize_type(data: JsonDict | str) -> Type:
200211
if isinstance(data, str):
201212
return Instance.deserialize(data)
@@ -991,13 +1002,20 @@ class TypeList(ProperType):
9911002
types before they are processed into Callable types.
9921003
"""
9931004

994-
__slots__ = ("items",)
1005+
__slots__ = ("items", "list_type")
9951006

9961007
items: list[Type]
9971008

998-
def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:
1009+
def __init__(
1010+
self,
1011+
items: list[Type],
1012+
list_type: int = TypeOfTypeList.callable_args,
1013+
line: int = -1,
1014+
column: int = -1,
1015+
) -> None:
9991016
super().__init__(line, column)
10001017
self.items = items
1018+
self.list_type = list_type
10011019

10021020
def accept(self, visitor: TypeVisitor[T]) -> T:
10031021
assert isinstance(visitor, SyntheticTypeVisitor)
@@ -1011,7 +1029,11 @@ def __hash__(self) -> int:
10111029
return hash(tuple(self.items))
10121030

10131031
def __eq__(self, other: object) -> bool:
1014-
return isinstance(other, TypeList) and self.items == other.items
1032+
return (
1033+
isinstance(other, TypeList)
1034+
and self.items == other.items
1035+
and self.list_type == other.list_type
1036+
)
10151037

10161038

10171039
class UnpackType(ProperType):
@@ -3043,6 +3065,8 @@ def visit_type_var(self, t: TypeVarType) -> str:
30433065
s = f"{t.name}`{t.id}"
30443066
if self.id_mapper and t.upper_bound:
30453067
s += f"(upper_bound={t.upper_bound.accept(self)})"
3068+
if t.has_default():
3069+
s += f" = {t.default.accept(self)}"
30463070
return s
30473071

30483072
def visit_param_spec(self, t: ParamSpecType) -> str:
@@ -3058,6 +3082,8 @@ def visit_param_spec(self, t: ParamSpecType) -> str:
30583082
s += f"{t.name_with_suffix()}`{t.id}"
30593083
if t.prefix.arg_types:
30603084
s += "]"
3085+
if t.has_default():
3086+
s += f" = {t.default.accept(self)}"
30613087
return s
30623088

30633089
def visit_parameters(self, t: Parameters) -> str:
@@ -3096,6 +3122,8 @@ def visit_type_var_tuple(self, t: TypeVarTupleType) -> str:
30963122
else:
30973123
# Named type variable type.
30983124
s = f"{t.name}`{t.id}"
3125+
if t.has_default():
3126+
s += f" = {t.default.accept(self)}"
30993127
return s
31003128

31013129
def visit_callable_type(self, t: CallableType) -> str:
@@ -3132,6 +3160,8 @@ def visit_callable_type(self, t: CallableType) -> str:
31323160
if s:
31333161
s += ", "
31343162
s += f"*{n}.args, **{n}.kwargs"
3163+
if param_spec.has_default():
3164+
s += f" = {param_spec.default.accept(self)}"
31353165

31363166
s = f"({s})"
31373167

@@ -3150,12 +3180,18 @@ def visit_callable_type(self, t: CallableType) -> str:
31503180
vals = f"({', '.join(val.accept(self) for val in var.values)})"
31513181
vs.append(f"{var.name} in {vals}")
31523182
elif not is_named_instance(var.upper_bound, "builtins.object"):
3153-
vs.append(f"{var.name} <: {var.upper_bound.accept(self)}")
3183+
vs.append(
3184+
f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3185+
)
31543186
else:
3155-
vs.append(var.name)
3187+
vs.append(
3188+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3189+
)
31563190
else:
3157-
# For other TypeVarLikeTypes, just use the name
3158-
vs.append(var.name)
3191+
# For other TypeVarLikeTypes, use the name and default
3192+
vs.append(
3193+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3194+
)
31593195
s = f"[{', '.join(vs)}] {s}"
31603196

31613197
return f"def {s}"

test-data/unit/check-parameter-specification.test

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ P = ParamSpec('P')
66
[case testInvalidParamSpecDefinitions]
77
from typing import ParamSpec
88

9-
P1 = ParamSpec("P1", covariant=True) # E: Only the first argument to ParamSpec has defined semantics
10-
P2 = ParamSpec("P2", contravariant=True) # E: Only the first argument to ParamSpec has defined semantics
11-
P3 = ParamSpec("P3", bound=int) # E: Only the first argument to ParamSpec has defined semantics
12-
P4 = ParamSpec("P4", int, str) # E: Only the first argument to ParamSpec has defined semantics
13-
P5 = ParamSpec("P5", covariant=True, bound=int) # E: Only the first argument to ParamSpec has defined semantics
9+
P1 = ParamSpec("P1", covariant=True) # E: The variance and bound arguments to ParamSpec do not have defined semantics yet
10+
P2 = ParamSpec("P2", contravariant=True) # E: The variance and bound arguments to ParamSpec do not have defined semantics yet
11+
P3 = ParamSpec("P3", bound=int) # E: The variance and bound arguments to ParamSpec do not have defined semantics yet
12+
P4 = ParamSpec("P4", int, str) # E: Only the first positional argument to ParamSpec has defined semantics
13+
P5 = ParamSpec("P5", covariant=True, bound=int) # E: The variance and bound arguments to ParamSpec do not have defined semantics yet
1414
[builtins fixtures/paramspec.pyi]
1515

1616
[case testParamSpecLocations]

0 commit comments

Comments
 (0)