Skip to content

Improve ParamSpec type inference from lambda #11602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3608,18 +3608,19 @@ def infer_lambda_type_using_context(self, e: LambdaExpr) -> Tuple[Optional[Calla

arg_kinds = [arg.kind for arg in e.arguments]

if callable_ctx.is_ellipsis_args:
if callable_ctx.is_ellipsis_args or ctx.param_spec() is not None:
# Fill in Any arguments to match the arguments of the lambda.
callable_ctx = callable_ctx.copy_modified(
is_ellipsis_args=False,
arg_types=[AnyType(TypeOfAny.special_form)] * len(arg_kinds),
arg_kinds=arg_kinds,
arg_names=[None] * len(arg_kinds)
arg_names=e.arg_names[:],
)

if ARG_STAR in arg_kinds or ARG_STAR2 in arg_kinds:
# TODO treat this case appropriately
return callable_ctx, None

if callable_ctx.arg_kinds != arg_kinds:
# Incompatible context; cannot use it to infer types.
self.chk.fail(message_registry.CANNOT_INFER_LAMBDA_TYPE, e)
Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-parameter-specification.test
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,21 @@ c2 = c
c3 = C(f)
c = c3
[builtins fixtures/dict.pyi]

[case testParamSpecInferredFromLambda]
from typing import Callable, TypeVar
from typing_extensions import ParamSpec

P = ParamSpec('P')
T = TypeVar('T')

# Similar to atexit.register
def register(f: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> Callable[P, T]: ... # N: "register" defined here

def f(x: int) -> None: pass

reveal_type(register(lambda: f(1))) # N: Revealed type is "def ()"
reveal_type(register(lambda x: f(x), x=1)) # N: Revealed type is "def (x: Any)"
register(lambda x: f(x)) # E: Missing positional argument "x" in call to "register"
register(lambda x: f(x), y=1) # E: Unexpected keyword argument "y" for "register"
[builtins fixtures/dict.pyi]