Skip to content

Commit eb7ba73

Browse files
committed
Add basic TypeVar defaults validation
1 parent f2f5810 commit eb7ba73

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
@@ -4098,28 +4098,17 @@ def process_typevar_parameters(
40984098
if has_values:
40994099
self.fail("TypeVar cannot have both values and an upper bound", context)
41004100
return None
4101-
try:
4102-
# We want to use our custom error message below, so we suppress
4103-
# the default error message for invalid types here.
4104-
analyzed = self.expr_to_analyzed_type(
4105-
param_value, allow_placeholder=True, report_invalid_types=False
4106-
)
4107-
if analyzed is None:
4108-
# Type variables are special: we need to place them in the symbol table
4109-
# soon, even if upper bound is not ready yet. Otherwise avoiding
4110-
# a "deadlock" in this common pattern would be tricky:
4111-
# T = TypeVar('T', bound=Custom[Any])
4112-
# class Custom(Generic[T]):
4113-
# ...
4114-
analyzed = PlaceholderType(None, [], context.line)
4115-
upper_bound = get_proper_type(analyzed)
4116-
if isinstance(upper_bound, AnyType) and upper_bound.is_from_error:
4117-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4118-
# Note: we do not return 'None' here -- we want to continue
4119-
# using the AnyType as the upper bound.
4120-
except TypeTranslationError:
4121-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4101+
tv_arg = self.get_typevarlike_argument("TypeVar", param_name, param_value, context)
4102+
if tv_arg is None:
41224103
return None
4104+
upper_bound = tv_arg
4105+
elif param_name == "default":
4106+
tv_arg = self.get_typevarlike_argument(
4107+
"TypeVar", param_name, param_value, context, allow_unbound_tvars=True
4108+
)
4109+
if tv_arg is None:
4110+
return None
4111+
default = tv_arg
41234112
elif param_name == "values":
41244113
# Probably using obsolete syntax with values=(...). Explain the current syntax.
41254114
self.fail('TypeVar "values" argument not supported', context)
@@ -4147,6 +4136,50 @@ def process_typevar_parameters(
41474136
variance = INVARIANT
41484137
return variance, upper_bound, default
41494138

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

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

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

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

4216-
if len(call.args) > 1:
4217-
self.fail("Only the first argument to TypeVarTuple has defined semantics", s)
4283+
n_values = call.arg_kinds[1:].count(ARG_POS)
4284+
if n_values != 0:
4285+
self.fail(
4286+
"Only the first positional argument to TypeVarTuple has defined semantics", s
4287+
)
42184288

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

42214312
if not self.incomplete_feature_enabled(TYPE_VAR_TUPLE, s):
42224313
return False
@@ -6310,6 +6401,8 @@ def expr_to_analyzed_type(
63106401
report_invalid_types: bool = True,
63116402
allow_placeholder: bool = False,
63126403
allow_type_any: bool = False,
6404+
allow_unbound_tvars: bool = False,
6405+
allow_param_spec_literals: bool = False,
63136406
) -> Type | None:
63146407
if isinstance(expr, CallExpr):
63156408
# This is a legacy syntax intended mostly for Python 2, we keep it for
@@ -6338,6 +6431,8 @@ def expr_to_analyzed_type(
63386431
report_invalid_types=report_invalid_types,
63396432
allow_placeholder=allow_placeholder,
63406433
allow_type_any=allow_type_any,
6434+
allow_unbound_tvars=allow_unbound_tvars,
6435+
allow_param_spec_literals=allow_param_spec_literals,
63416436
)
63426437

63436438
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):
@@ -3037,6 +3059,8 @@ def visit_type_var(self, t: TypeVarType) -> str:
30373059
s = f"{t.name}`{t.id}"
30383060
if self.id_mapper and t.upper_bound:
30393061
s += f"(upper_bound={t.upper_bound.accept(self)})"
3062+
if t.has_default():
3063+
s += f" = {t.default.accept(self)}"
30403064
return s
30413065

30423066
def visit_param_spec(self, t: ParamSpecType) -> str:
@@ -3052,6 +3076,8 @@ def visit_param_spec(self, t: ParamSpecType) -> str:
30523076
s += f"{t.name_with_suffix()}`{t.id}"
30533077
if t.prefix.arg_types:
30543078
s += "]"
3079+
if t.has_default():
3080+
s += f" = {t.default.accept(self)}"
30553081
return s
30563082

30573083
def visit_parameters(self, t: Parameters) -> str:
@@ -3090,6 +3116,8 @@ def visit_type_var_tuple(self, t: TypeVarTupleType) -> str:
30903116
else:
30913117
# Named type variable type.
30923118
s = f"{t.name}`{t.id}"
3119+
if t.has_default():
3120+
s += f" = {t.default.accept(self)}"
30933121
return s
30943122

30953123
def visit_callable_type(self, t: CallableType) -> str:
@@ -3126,6 +3154,8 @@ def visit_callable_type(self, t: CallableType) -> str:
31263154
if s:
31273155
s += ", "
31283156
s += f"*{n}.args, **{n}.kwargs"
3157+
if param_spec.has_default():
3158+
s += f" = {param_spec.default.accept(self)}"
31293159

31303160
s = f"({s})"
31313161

@@ -3144,12 +3174,18 @@ def visit_callable_type(self, t: CallableType) -> str:
31443174
vals = f"({', '.join(val.accept(self) for val in var.values)})"
31453175
vs.append(f"{var.name} in {vals}")
31463176
elif not is_named_instance(var.upper_bound, "builtins.object"):
3147-
vs.append(f"{var.name} <: {var.upper_bound.accept(self)}")
3177+
vs.append(
3178+
f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3179+
)
31483180
else:
3149-
vs.append(var.name)
3181+
vs.append(
3182+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3183+
)
31503184
else:
3151-
# For other TypeVarLikeTypes, just use the name
3152-
vs.append(var.name)
3185+
# For other TypeVarLikeTypes, use the name and default
3186+
vs.append(
3187+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3188+
)
31533189
s = f"[{', '.join(vs)}] {s}"
31543190

31553191
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)