Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9773e70

Browse files
Fix ParamSpec constraint for types as callable
Most types can be considered as callables, constructing the type itself. When a constraint was created for a ParamSpec variable, the return type would be set to NoneType, which conflicts with assumptions that CallableType makes when it is the constructor of another type, crashing mypy. This patch replaces the return type by UninhabitedType instead, which stops CallableType from considering itself as a constructor.
1 parent e814c47 commit 9773e70

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

mypy/constraints.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -954,7 +954,7 @@ def visit_callable_type(self, template: CallableType) -> list[Constraint]:
954954
arg_types=cactual.arg_types[prefix_len:],
955955
arg_kinds=cactual.arg_kinds[prefix_len:],
956956
arg_names=cactual.arg_names[prefix_len:],
957-
ret_type=NoneType(),
957+
ret_type=UninhabitedType(),
958958
),
959959
)
960960
)

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1296,3 +1296,26 @@ class C(Generic[P]):
12961296

12971297
reveal_type(bar(C(fn=foo, x=1))) # N: Revealed type is "__main__.C[[x: builtins.int]]"
12981298
[builtins fixtures/paramspec.pyi]
1299+
1300+
[case testParamSpecClassConstructor]
1301+
from typing import ParamSpec, Callable
1302+
1303+
P = ParamSpec("P")
1304+
1305+
class SomeClass:
1306+
def __init__(self, a: str) -> None:
1307+
pass
1308+
1309+
def func(t: Callable[P, SomeClass], val: Callable[P, SomeClass]) -> None:
1310+
pass
1311+
1312+
def constructor(a: str) -> SomeClass:
1313+
return SomeClass(a)
1314+
1315+
def wrong_constructor(a: bool) -> SomeClass:
1316+
return SomeClass("a")
1317+
1318+
func(SomeClass, constructor)
1319+
func(SomeClass, wrong_constructor) # E: Argument 1 to "func" has incompatible type "Type[SomeClass]"; expected "Callable[[VarArg(None), KwArg(None)], SomeClass]" \
1320+
# E: Argument 2 to "func" has incompatible type "Callable[[bool], SomeClass]"; expected "Callable[[VarArg(None), KwArg(None)], SomeClass]"
1321+
[builtins fixtures/paramspec.pyi]

0 commit comments

Comments
 (0)