Skip to content
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

Incorrect type narrowing for inspect.isawaitable #15520

Closed
heckad opened this issue Jun 26, 2023 · 2 comments
Closed

Incorrect type narrowing for inspect.isawaitable #15520

heckad opened this issue Jun 26, 2023 · 2 comments
Labels
bug mypy got something wrong topic-typeguard TypeGuard / PEP 647

Comments

@heckad
Copy link

heckad commented Jun 26, 2023

Bug Report
https://mypy-play.net/?mypy=1.4.0&python=3.10&gist=5ab30e161d5e83a16538d790c9c2deb9

Expected Behavior

No errors

Actual Behavior

Error

@heckad heckad added the bug mypy got something wrong label Jun 26, 2023
@AlexWaygood AlexWaygood added the topic-typeguard TypeGuard / PEP 647 label Jun 26, 2023
@AlexWaygood
Copy link
Member

Mypy's behaviour is correct here, as inspect.isawaitable is annotated using TypeGuard in typeshed, and TypeGuard doesn't apply type narrowing in the negative case (only in the positive case). This is specified in PEP 674 and is implemented correctly by mypy.

There has been discussion of a stricter version of TypeGuard that could apply type narrowing in the negative case (python/typing#996, python/typing#926), which you might be interested in. However, that would be a new feature in the typing system, so can't be done currently.

@AlexWaygood AlexWaygood closed this as not planned Won't fix, can't repro, duplicate, stale Jun 26, 2023
@AlexWaygood
Copy link
Member

To make your code pass mypy in the meantime, you can do this:

 import inspect
 from typing import Awaitable

 async def f(t: Awaitable[int] | int) -> int:
     if inspect.isawaitable(t):
         return await t
     else:
+        assert isinstance(t, int)
         return t

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-typeguard TypeGuard / PEP 647
Projects
None yet
Development

No branches or pull requests

2 participants