python / python/mypy

Error with Protocols and AsyncContextManager

Abierto
#8,276 10 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

documentation needs discussion topic-usability
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

  • 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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Empieza guardando el ejemplo proporcionado como bug.py y ejecutando mypy bug.py con la versión indicada y sin flags. Sigue cómo mypy comprueba los métodos de Protocol, los tipos de retorno asíncronos y los gestores de contexto asíncronos. Se considera terminado cuando el ejemplo no produce errores y conserva el comportamiento esperado de comprobación de tipos.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.