Skip to content

Commit e8bbe5c

Browse files
committed
Add basic TypeVar defaults validation
1 parent bca0afc commit e8bbe5c

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

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

4186-
# ParamSpec is different from a regular TypeVar:
4187-
# arguments are not semantically valid. But, allowed in runtime.
4188-
# So, we need to warn users about possible invalid usage.
4189-
if len(call.args) > 1:
4190-
self.fail("Only the first argument to ParamSpec has defined semantics", s)
4219+
n_values = call.arg_kinds[1:].count(ARG_POS)
4220+
if n_values != 0:
4221+
self.fail("Only the first positional argument to ParamSpec has defined semantics", s)
41914222

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

41944261
# PEP 612 reserves the right to define bound, covariant and contravariant arguments to
41954262
# ParamSpec in a later PEP. If and when that happens, we should do something
@@ -4217,10 +4284,34 @@ def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool:
42174284
if not call:
42184285
return False
42194286

4220-
if len(call.args) > 1:
4221-
self.fail("Only the first argument to TypeVarTuple has defined semantics", s)
4287+
n_values = call.arg_kinds[1:].count(ARG_POS)
4288+
if n_values != 0:
4289+
self.fail(
4290+
"Only the first positional argument to TypeVarTuple has defined semantics", s
4291+
)
42224292

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

42254316
if not self.incomplete_feature_enabled(TYPE_VAR_TUPLE, s):
42264317
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,
@@ -891,10 +892,12 @@ def visit_type_list(self, t: TypeList) -> Type:
891892
else:
892893
return AnyType(TypeOfAny.from_error)
893894
else:
895+
s = "[...]" if t.list_type == TypeOfTypeList.callable_args else "(...)"
894896
self.fail(
895-
'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE
897+
f'Bracketed expression "{s}" is not valid as a type', t, code=codes.VALID_TYPE
896898
)
897-
self.note('Did you mean "List[...]"?', t)
899+
if t.list_type == TypeOfTypeList.callable_args:
900+
self.note('Did you mean "List[...]"?', t)
898901
return AnyType(TypeOfAny.from_error)
899902

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