python / python/mypy

Error with Protocols and AsyncContextManager

Open
#8,276 10 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

documentation needs discussion topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

  • Are you reporting a bug, or opening a feature request?
    A bug

  • Please insert below the code you are checking with mypy,

from __future__ import annotations

import asyncio
import typing as t
from contextlib import asynccontextmanager

import typing_extensions as te


class LockProto(te.Protocol):
    async def with_lock(self) -> t.AsyncContextManager[str]: ...


class Consumer:
    def __init__(self, locker: LockProto) -> None:
        self.locker = locker

    def run(self) -> None:
        async with self.locker.with_lock() as name:
            print(name)


class SockLock:
    @asynccontextmanager
    async def with_lock(self) -> t.AsyncGenerator[str, None]:
        yield 'some-string'


async def main() -> None:
    cons = Consumer(SockLock())
    await cons.run()


if __name__ == '__main__':
    asyncio.run(main())
  • What is the actual behavior/output?
bug.py:18: error: "Coroutine[Any, Any, AsyncContextManager[str]]" has no attribute "__enter__"
bug.py:18: error: "Coroutine[Any, Any, AsyncContextManager[str]]" has no attribute "__exit__"
bug.py:29: error: Argument 1 to "Consumer" has incompatible type "SockLock"; expected "LockProto"
bug.py:29: note: Following member(s) of "SockLock" have conflicts:
bug.py:29: note:     Expected:
bug.py:29: note:         def with_lock(self) -> Coroutine[Any, Any, AsyncContextManager[str]]
bug.py:29: note:     Got:
bug.py:29: note:         def with_lock(*Any, **Any) -> AsyncContextManager[Any]
  • What is the behavior/output you expect?
    No errors

  • What are the versions of mypy and Python you are using?
    0.761

  • What are the mypy flags you are using? (For example --strict-optional)
    No flags, just mypy bug.py

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by saving the supplied example as bug.py and running mypy bug.py with the reported version and no flags. Trace how mypy checks Protocol methods, async return types, and async context managers. Done means the example produces no errors while preserving the expected type checking behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.