python / python/mypy

mypy suggests `Iterator[Never]`, wants `Iterator[None]` as return type of contextmanager

Open
#18,086 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-error-reporting
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

A superficial take on a context manager (https://mypy-play.net/?mypy=latest&python=3.12&gist=68fae9f1b14467dc3a586f2473c9c419):

from contextlib import contextmanager


@contextmanager
def foo() -> None:
    yield

results in:

main.py:4: error: Argument 1 to "contextmanager" has incompatible type "Callable[[], None]"; expected "Callable[[], Iterator[Never]]"  [arg-type]
main.py:5: error: The return type of a generator function should be "Generator" or one of its supertypes  [misc]

If I specify Iterator[Never] as suggested, it still doesn't work (https://mypy-play.net/?mypy=latest&python=3.12&gist=d644d5c880c5f04b0c54941a7cc8c4b2):

from contextlib import contextmanager
from typing import Iterator, Never


@contextmanager
def foo() -> Iterator[Never]:
    yield

results in:

main.py:7: error: Yield value expected  [misc]

Inspired by https://github.com/python/mypy/issues/3551 I switched it to None (https://mypy-play.net/?mypy=latest&python=3.12&gist=e825ee207b3fbcad373163f5618f467e):

from contextlib import contextmanager
from typing import Iterator, Never


@contextmanager
def foo() -> Iterator[None]:
    yield

And now it works:

Success: no issues found in 1 source file

How? Wasn't Never (as in "never returns") supposed to not ask for a return value?

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

Reproduce the three snippets using the linked mypy-play examples, then trace mypy's handling of generator return annotations and contextlib.contextmanager. Done means the diagnostics correctly explain the valid Iterator[None] annotation and no longer suggest an unusable Iterator[Never] annotation.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.