Rule Proposal: Enforce generator
on contextlib.contextmanager
decorated functions
#11686
Labels
rule
Implementing or modifying a lint rule
In the past, it was fairly common for people to simply put
Iterator
on context managers simply out of convenience, as typing outGenerator
, required adding in two (mostly useless) generic params. However, this can lead to runtime failures not caught by a type-checker, take this example from python/typeshed#2772.Due to how breaking this change is, the typeshed maintainers were are reluctant to change the underlying annotation to require a
Generator
. It was actually proposed offloading this responsibility to linting tules, or special rules within the type-checkers themselves.Now,
Iterator[int]
can be simplified toGenerator[int]
with the addition of type var defaults, and their usage in the cpython implementation, and the typesheds, see: python/typeshed#11867I would propose adding a rule to autofix
Iterator[T]
toGenerator[T]
on 3.13+ for any functions decorated withcontextlib.contextmanager
, or when deferred annotations are present in the file, as otherwise a runtime error will be encountered. In cases where neither are true, an error can simply be flagged and fixed manually (either through quotingGenerator[T]
, or doingGenerator[T, None, None]
).This will help ensure that type-checkers such as Pyright and MyPy can flag and catch issues that might be hidden as a result.
The text was updated successfully, but these errors were encountered: