Skip to content

Cannot infer type of lambda regression with mypy 1.9 #17018

Open

Description

@rbuffat

Bug Report

The lambda in the following code snippet reports error: Cannot infer type of lambda starting from mypy 1.9.0 (It did not report an error with mypy 1.8.0).

#15459 seems related, but it looks as mypy 1.8.0 also reported an error there.

To Reproduce

import asyncio
import signal


async def shutdown(
    signal: signal.Signals,
) -> None:
    print(signal.name)


async def main() -> None:
    loop = asyncio.get_event_loop()
    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
    for s in signals:
        loop.add_signal_handler(
            s,
            lambda s=s: asyncio.create_task(  #  <-- error: Cannot infer type of lambda  [misc]
                shutdown(
                    signal=s,
                ),
                name="shutdown",
            ),
        )

mypy playground

Expected Behavior

No error shown regarding the lambda.

Actual Behavior

mypy reports Cannot infer type of lambda [misc]

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.11.8

Activity

  1. AlexWaygood commented on Mar 12, 2024

    @AlexWaygood
    Member

    Here's a mimimal repro of the underlying issue that doesn't involve typeshed's stubs for asyncio:

    from typing import TypeVarTuple, Callable
    
    x = 42
    Ts = TypeVarTuple("Ts")
    
    def foo(cb: Callable[[*Ts], object], *args: *Ts) -> None: ...
    foo(lambda x=x: None)  # error: Cannot infer type of lambda  [misc]

    https://mypy-play.net/?mypy=latest&python=3.12&gist=ce433643f1bff8c03f6f8149f7829793

    (The immediate cause of the new false positive was python/typeshed@a08d2d5, but the underlying issue is mypy struggling to solve a TypeVarTuple when you're passing in a lambda.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-646PEP 646 (TypeVarTuple, Unpack)

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions