Skip to content

Commit f8e8f66

Browse files
committed
Add basic TypeVar defaults validation
1 parent ccc0eef commit f8e8f66

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

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

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

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

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

4218-
if len(call.args) > 1:
4219-
self.fail("Only the first argument to TypeVarTuple has defined semantics", s)
4285+
n_values = call.arg_kinds[1:].count(ARG_POS)
4286+
if n_values != 0:
4287+
self.fail(
4288+
"Only the first positional argument to TypeVarTuple has defined semantics", s
4289+
)
42204290

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

42234314
if not self.incomplete_feature_enabled(TYPE_VAR_TUPLE, s):
42244315
return False
@@ -6311,6 +6402,8 @@ def expr_to_analyzed_type(
63116402
report_invalid_types: bool = True,
63126403
allow_placeholder: bool = False,
63136404
allow_type_any: bool = False,
6405+
allow_unbound_tvars: bool = False,
6406+
allow_param_spec_literals: bool = False,
63146407
) -> Type | None:
63156408
if isinstance(expr, CallExpr):
63166409
# This is a legacy syntax intended mostly for Python 2, we keep it for
@@ -6339,6 +6432,8 @@ def expr_to_analyzed_type(
63396432
report_invalid_types=report_invalid_types,
63406433
allow_placeholder=allow_placeholder,
63416434
allow_type_any=allow_type_any,
6435+
allow_unbound_tvars=allow_unbound_tvars,
6436+
allow_param_spec_literals=allow_param_spec_literals,
63426437
)
63436438

63446439
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)
@@ -990,13 +1001,20 @@ class TypeList(ProperType):
9901001
types before they are processed into Callable types.
9911002
"""
9921003

993-
__slots__ = ("items",)
1004+
__slots__ = ("items", "list_type")
9941005

9951006
items: list[Type]
9961007

997-
def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:
1008+
def __init__(
1009+
self,
1010+
items: list[Type],
1011+
list_type: int = TypeOfTypeList.callable_args,
1012+
line: int = -1,
1013+
column: int = -1,
1014+
) -> None:
9981015
super().__init__(line, column)
9991016
self.items = items
1017+
self.list_type = list_type
10001018

10011019
def accept(self, visitor: TypeVisitor[T]) -> T:
10021020
assert isinstance(visitor, SyntheticTypeVisitor)
@@ -1010,7 +1028,11 @@ def __hash__(self) -> int:
10101028
return hash(tuple(self.items))
10111029

10121030
def __eq__(self, other: object) -> bool:
1013-
return isinstance(other, TypeList) and self.items == other.items
1031+
return (
1032+
isinstance(other, TypeList)
1033+
and self.items == other.items
1034+
and self.list_type == other.list_type
1035+
)
10141036

10151037

10161038
class UnpackType(ProperType):
@@ -3036,6 +3058,8 @@ def visit_type_var(self, t: TypeVarType) -> str:
30363058
s = f"{t.name}`{t.id}"
30373059
if self.id_mapper and t.upper_bound:
30383060
s += f"(upper_bound={t.upper_bound.accept(self)})"
3061+
if t.has_default():
3062+
s += f" = {t.default.accept(self)}"
30393063
return s
30403064

30413065
def visit_param_spec(self, t: ParamSpecType) -> str:
@@ -3051,6 +3075,8 @@ def visit_param_spec(self, t: ParamSpecType) -> str:
30513075
s += f"{t.name_with_suffix()}`{t.id}"
30523076
if t.prefix.arg_types:
30533077
s += "]"
3078+
if t.has_default():
3079+
s += f" = {t.default.accept(self)}"
30543080
return s
30553081

30563082
def visit_parameters(self, t: Parameters) -> str:
@@ -3089,6 +3115,8 @@ def visit_type_var_tuple(self, t: TypeVarTupleType) -> str:
30893115
else:
30903116
# Named type variable type.
30913117
s = f"{t.name}`{t.id}"
3118+
if t.has_default():
3119+
s += f" = {t.default.accept(self)}"
30923120
return s
30933121

30943122
def visit_callable_type(self, t: CallableType) -> str:
@@ -3125,6 +3153,8 @@ def visit_callable_type(self, t: CallableType) -> str:
31253153
if s:
31263154
s += ", "
31273155
s += f"*{n}.args, **{n}.kwargs"
3156+
if param_spec.has_default():
3157+
s += f" = {param_spec.default.accept(self)}"
31283158

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

@@ -3143,12 +3173,18 @@ def visit_callable_type(self, t: CallableType) -> str:
31433173
vals = f"({', '.join(val.accept(self) for val in var.values)})"
31443174
vs.append(f"{var.name} in {vals}")
31453175
elif not is_named_instance(var.upper_bound, "builtins.object"):
3146-
vs.append(f"{var.name} <: {var.upper_bound.accept(self)}")
3176+
vs.append(
3177+
f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3178+
)
31473179
else:
3148-
vs.append(var.name)
3180+
vs.append(
3181+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3182+
)
31493183
else:
3150-
# For other TypeVarLikeTypes, just use the name
3151-
vs.append(var.name)
3184+
# For other TypeVarLikeTypes, use the name and default
3185+
vs.append(
3186+
f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3187+
)
31523188
s = f"[{', '.join(vs)}] {s}"
31533189

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