stubgen generates stubs for `@asynccontextmanager` functions that mypy itself rejects

Ouverte
#21,869 3 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Évaluation

Difficulté
3/5
Temps estimé
1-2 jours
Accessibilité débutants
72/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Calme
Stack technique
python
Domaine
cli, tooling

Piste de recherche

Commencez par le point d’entrée de stubgen et reproduisez le problème avec cm.py, l’exemple @asynccontextmanager du rapport. Comparez la sortie .pyi générée pour les fonctions et méthodes génératrices asynchrones, puis exécutez mypy sur le stub généré. Le travail est terminé lorsque le stub généré pour ce cas passe la vérification de types sans erreur tout en préservant le typage prévu du gestionnaire de contexte.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

bug topic-stubgen

Bug Report

stubgen copies @asynccontextmanager and the async def keyword verbatim into the generated .pyi. Because a stub body has no yield, mypy then classifies the stubbed function as a coroutine function returning AsyncIterator[T] rather than as an async generator function, and rejects the decorator application.

The result is that stubgen emits a stub which mypy — the same version, with default settings — reports an error on. Source that type-checks cleanly produces a stub that does not.

To Reproduce

# cm.py
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager


@asynccontextmanager
async def ctx() -> AsyncIterator[int]:
    yield 1
$ mypy cm.py
Success: no issues found in 1 source file

$ stubgen -o out cm.py
Processed 1 modules
Generated out/cm.pyi

$ cat out/cm.pyi
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

@asynccontextmanager
async def ctx() -> AsyncIterator[int]: ...

$ mypy out/cm.pyi
out/cm.pyi:4: error: Argument 1 to "asynccontextmanager" has incompatible type "Callable[[], Coroutine[Any, Any, AsyncIterator[int]]]"; expected "Callable[[], AsyncIterator[Never]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

The same happens for methods, and with AsyncGenerator[T, None] in place of AsyncIterator[T].

Expected Behavior

stubgen output should type-check under the mypy version that produced it. For an @asynccontextmanager-decorated async generator, that means emitting one of the two spellings the typing docs sanction for stubs — either dropping async:

@asynccontextmanager
def ctx() -> AsyncIterator[int]: ...

or dropping the decorator and declaring the decorated result, as typeshed does:

from contextlib import AbstractAsyncContextManager

def ctx() -> AbstractAsyncContextManager[int]: ...

Both of these are accepted by mypy 2.3.0.

Actual Behavior

out/cm.pyi:4: error: Argument 1 to "asynccontextmanager" has incompatible type "Callable[[], Coroutine[Any, Any, AsyncIterator[int]]]"; expected "Callable[[], AsyncIterator[Never]]"  [arg-type]

Your Environment

  • Mypy version used: 2.3.0 (compiled: yes)
  • Mypy command-line flags: none (mypy out/cm.pyi); stub produced with stubgen -o out cm.py
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.15

Additional notes

This is a change in behaviour from 1.15.0. That version's stubgen omitted the decorator entirely:

# stubgen 1.15.0
async def ctx() -> AsyncIterator[int]: ...

which is also lossy, but happens to type-check, so the problem only becomes visible on 2.3.0 once the decorator is preserved.

The synchronous case is unaffected — @contextmanager over def f() -> Iterator[T] round-trips through stubgen and type-checks on 2.3.0, because there is no async keyword to change how the return type is interpreted.

Langage dominant
Python
Étoiles
20.6k
Forks
3.3k
Merge moyen
1 j 18 h
PR mergées (30 j)
54

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de python/mypy

Toutes les issues de python/mypy

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.