Skip to content

Commit 5c29737

Browse files
committed
Add basic TypeVar defaults validation
1 parent e5d9c3c commit 5c29737

File tree

8 files changed

+257
-46
lines changed

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
@@ -181,7 +181,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
181181
INVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of "{}" must be a subtype of {}'
182182
INVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for "{}"'
183183
TYPEVAR_VARIANCE_DEF: Final = 'TypeVar "{}" may only be a literal bool'
184-
TYPEVAR_BOUND_MUST_BE_TYPE: Final = 'TypeVar "bound" must be a type'
184+
TYPEVAR_ARG_MUST_BE_TYPE: Final = '{} "{}" must be a type'
185185
TYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to "TypeVar()"'
186186
UNBOUND_TYPEVAR: Final = (
187187
"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
@@ -4106,28 +4106,17 @@ def process_typevar_parameters(
41064106
if has_values:
41074107
self.fail("TypeVar cannot have both values and an upper bound", context)
41084108
return None
4109-
try:
4110-
# We want to use our custom error message below, so we suppress
4111-
# the default error message for invalid types here.
4112-
analyzed = self.expr_to_analyzed_type(
4113-
param_value, allow_placeholder=True, report_invalid_types=False
4114-
)
4115-
if analyzed is None:
4116-
# Type variables are special: we need to place them in the symbol table
4117-
# soon, even if upper bound is not ready yet. Otherwise avoiding
4118-
# a "deadlock" in this common pattern would be tricky:
4119-
# T = TypeVar('T', bound=Custom[Any])
4120-
# class Custom(Generic[T]):
4121-
# ...
4122-
analyzed = PlaceholderType(None, [], context.line)
4123-
upper_bound = get_proper_type(analyzed)
4124-
if isinstance(upper_bound, AnyType) and upper_bound.is_from_error:
4125-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4126-
# Note: we do not return 'None' here -- we want to continue
4127-
# using the AnyType as the upper bound.
4128-
except TypeTranslationError:
4129-
self.fail(message_registry.TYPEVAR_BOUND_MUST_BE_TYPE, param_value)
4109+
tv_arg = self.get_typevarlike_argument("TypeVar", param_name, param_value, context)
4110+
if tv_arg is None:
41304111
return None
4112+
upper_bound = tv_arg
4113+
elif param_name == "default":
4114+
tv_arg = self.get_typevarlike_argument(
4115+
"TypeVar", param_name, param_value, context, allow_unbound_tvars=True
4116+
)
4117+
if tv_arg is None:
4118+
return None
4119+
default = tv_arg
41314120
elif param_name == "values":
41324121
# Probably using obsolete syntax with values=(...). Explain the current syntax.
41334122
self.fail('TypeVar "values" argument not supported', context)
@@ -4155,6 +4144,50 @@ def process_typevar_parameters(
41554144
variance = INVARIANT
41564145
return variance, upper_bound, default
41574146

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

4190-
# ParamSpec is different from a regular TypeVar:
4191-
# arguments are not semantically valid. But, allowed in runtime.
4192-
# So, we need to warn users about possible invalid usage.
4193-
if len(call.args) > 1:
4194-
self.fail("Only the first argument to ParamSpec has defined semantics", s)
4223+
n_values = call.arg_kinds[1:].count(ARG_POS)
4224+
if n_values != 0:
4225+
self.fail("Only the first positional argument to ParamSpec has defined semantics", s)
41954226

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

41984265
# PEP 612 reserves the right to define bound, covariant and contravariant arguments to
41994266
# ParamSpec in a later PEP. If and when that happens, we should do something
@@ -4227,10 +4294,34 @@ def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool:
42274294
if not call:
42284295
return False
42294296

4230-
if len(call.args) > 1:
4231-
self.fail("Only the first argument to TypeVarTuple has defined semantics", s)
4297+
n_values = call.arg_kinds[1:].count(ARG_POS)
4298+
if n_values != 0:
4299+
self.fail(
4300+
"Only the first positional argument to TypeVarTuple has defined semantics", s
4301+
)
42324302

42334303
default: Type = AnyType(TypeOfAny.from_omitted_generics)
4304+
for param_value, param_name in zip(
4305+
call.args[1 + n_values :], call.arg_names[1 + n_values :]
4306+
):
4307+
if param_name == "default":
4308+
tv_arg = self.get_typevarlike_argument(
4309+
"TypeVarTuple", param_name, param_value, s, allow_unbound_tvars=True
4310+
)
4311+
if tv_arg is None:
4312+
return False
4313+
default = tv_arg
4314+
if not isinstance(default, UnpackType):
4315+
self.fail(
4316+
"The default argument to TypeVarTuple must be an Unpacked tuple",
4317+
param_value,
4318+
)
4319+
default = AnyType(TypeOfAny.from_error)
4320+
else:
4321+
self.fail(
4322+
"The variance and bound arguments to TypeVarTuple do not have defined semantics yet",
4323+
s,
4324+
)
42344325

42354326
if not self.incomplete_feature_enabled(TYPE_VAR_TUPLE, s):
42364327
return False
@@ -6324,6 +6415,8 @@ def expr_to_analyzed_type(
63246415
report_invalid_types: bool = True,
63256416
allow_placeholder: bool = False,
63266417
allow_type_any: bool = False,
6418+
allow_unbound_tvars: bool = False,
6419+
allow_param_spec_literals: bool = False,
63276420
) -> Type | None:
63286421
if isinstance(expr, CallExpr):
63296422
# This is a legacy syntax intended mostly for Python 2, we keep it for
@@ -6352,6 +6445,8 @@ def expr_to_analyzed_type(
63526445
report_invalid_types=report_invalid_types,
63536446
allow_placeholder=allow_placeholder,
63546447
allow_type_any=allow_type_any,
6448+
allow_unbound_tvars=allow_unbound_tvars,
6449+
allow_param_spec_literals=allow_param_spec_literals,
63556450
)
63566451

63576452
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,
@@ -896,10 +897,12 @@ def visit_type_list(self, t: TypeList) -> Type:
896897
else:
897898
return AnyType(TypeOfAny.from_error)
898899
else:
900+
s = "[...]" if t.list_type == TypeOfTypeList.callable_args else "(...)"
899901
self.fail(
900-
'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE
902+
f'Bracketed expression "{s}" is not valid as a type', t, code=codes.VALID_TYPE
901903
)
902-
self.note('Did you mean "List[...]"?', t)
904+
if t.list_type == TypeOfTypeList.callable_args:
905+
self.note('Did you mean "List[...]"?', t)
903906
return AnyType(TypeOfAny.from_error)
904907

905908
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
@@ -197,6 +197,17 @@ class TypeOfAny:
197197
suggestion_engine: Final = 9
198198

199199

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

997-
__slots__ = ("items",)
1008+
__slots__ = ("items", "list_type")
9981009

9991010
items: list[Type]
10001011

1001-
def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:
1012+
def __init__(
1013+
self,
1014+
items: list[Type],
1015+
list_type: int = TypeOfTypeList.callable_args,
1016+
line: int = -1,
1017+
column: int = -1,
1018+
) -> None:
10021019
super().__init__(line, column)
10031020
self.items = items
1021+
self.list_type = list_type
10041022

10051023
def accept(self, visitor: TypeVisitor[T]) -> T:
10061024
assert isinstance(visitor, SyntheticTypeVisitor)
@@ -1014,7 +1032,11 @@ def __hash__(self) -> int:
10141032
return hash(tuple(self.items))
10151033

10161034
def __eq__(self, other: object) -> bool:
1017-
return isinstance(other, TypeList) and self.items == other.items
1035+
return (
1036+
isinstance(other, TypeList)
1037+
and self.items == other.items
1038+
and self.list_type == other.list_type
1039+
)
10181040

10191041

10201042
class UnpackType(ProperType):
@@ -3041,6 +3063,8 @@ def visit_type_var(self, t: TypeVarType) -> str:
30413063
s = f"{t.name}`{t.id}"
30423064
if self.id_mapper and t.upper_bound:
30433065
s += f"(upper_bound={t.upper_bound.accept(self)})"
3066+
if t.has_default():
3067+
s += f" = {t.default.accept(self)}"
30443068
return s
30453069

30463070
def visit_param_spec(self, t: ParamSpecType) -> str:
@@ -3056,6 +3080,8 @@ def visit_param_spec(self, t: ParamSpecType) -> str:
30563080
s += f"{t.name_with_suffix()}`{t.id}"
30573081
if t.prefix.arg_types:
30583082
s += "]"
3083+
if t.has_default():
3084+
s += f" = {t.default.accept(self)}"
30593085
return s
30603086

30613087
def visit_parameters(self, t: Parameters) -> str:
@@ -3094,6 +3120,8 @@ def visit_type_var_tuple(self, t: TypeVarTupleType) -> str:
30943120
else:
30953121
# Named type variable type.
30963122
s = f"{t.name}`{t.id}"
3123+
if t.has_default():
3124+
s += f" = {t.default.accept(self)}"
30973125
return s
30983126

30993127
def visit_callable_type(self, t: CallableType) -> str:
@@ -3130,6 +3158,8 @@ def visit_callable_type(self, t: CallableType) -> str:
31303158
if s:
31313159
s += ", "
31323160
s += f"*{n}.args, **{n}.kwargs"
3161+
if param_spec.has_default():
3162+
s += f" = {param_spec.default.accept(self)}"
31333163

31343164
s = f"({s})"
31353165

@@ -3148,12 +3178,18 @@ def visit_callable_type(self, t: CallableType) -> str:
31483178
vals = f"({', '.join(val.accept(self) for val in var.values)})"
31493179
vs.append(f"{var.name} in {vals}")
31503180
elif not is_named_instance(var.upper_bound, "builtins.object"):
3151-
vs.append(f"{var.name} <: {var.upper_bound.accept(self)}")
3181+
vs.append(
3182+
f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3183+
)
31523184
else:
3153-
vs.append(var.name)
3185+
vs.append(
3186+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3187+
)
31543188
else:
3155-
# For other TypeVarLikeTypes, just use the name
3156-
vs.append(var.name)
3189+
# For other TypeVarLikeTypes, use the name and default
3190+
vs.append(
3191+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3192+
)
31573193
s = f"[{', '.join(vs)}] {s}"
31583194

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