Cannot set return type of asynccontextmanagers in Protocol classes
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When decorating an empty method ("...") inside of a Protocol definition as an asynccontextmanager, the type checker insists that the return type must use Never instead of allowing to specify the type intended by the protocol.
To Reproduce
See also in Playground.
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Protocol
class P(Protocol):
@asynccontextmanager
async def f(self) -> AsyncIterator[None]:
"""Create a context but yield nothing."""
...
Importing AsyncIterator from typing instead of collections.abc makes no difference.
Expected Behavior
I should be allowed to annotate the expected yield-Type of the context manager in a Protocol without having to provide an implementation. (None in this case, but also any other type that the context will yield to the with statement.)
Actual Behavior
Produces this error:
main.py:7: error: Argument 1 to "asynccontextmanager" has incompatible type "Callable[[P], Coroutine[Any, Any, AsyncIterator[None]]]"; expected "Callable[[P], AsyncIterator[Never]]" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.12.0
- Mypy command-line flags: (None)
- Mypy configuration options from
mypy.ini(and other config files): (see below) - Python version used: 3.12.4
My mypy config (but it also reproduces when leaving all options unchecked in the Playground):
[tool.mypy]
ignore_missing_imports = false
disallow_untyped_calls = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
disallow_any_unimported = true
strict_optional = true
no_implicit_optional = true
check_untyped_defs = true
show_error_codes = true
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_return_any = true
warn_unreachable = true
strict_equality = true
strict = true
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the diagnostic with the Python 3.12 example in the issue or linked Playground, then trace mypy's handling of @asynccontextmanager on an empty Protocol method. Done when the example accepts AsyncIterator[None] and analogous yield types without the reported arg-type error, with a regression test covering it.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100