python / python/mypy

overload and contextmanager doesn't work together

Open
#14,652 8 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug documentation
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

contextmanager and overload doesn't seem to be compatbile together

To Reproduce

from contextlib import contextmanager
from typing import overload, ContextManager, Iterator
from uuid import UUID

@overload
def cactus() -> ContextManager[int]:
    ...

@overload
def cactus(_id: str) -> ContextManager[UUID]:
    ...

@contextmanager
def cactus(_id: str | None = None) -> Iterator[UUID] | Iterator[int]:
    if not _id:
        yield 1
    yield UUID(_id)

Expected Behavior

Mypy should find no issue

Actual Behavior

test.py: note: In function "cactus":
test.py:16:2: error: Overloaded function implementation cannot produce return type of signature 1  [misc]
    @contextmanager
     ^
test.py:16:2: error: Overloaded function implementation cannot produce return type of signature 2  [misc]
    @contextmanager
     ^
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.0.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10.6

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 reproducing the supplied Python 3.10.6 example with mypy 1.0.0, focusing on the interaction between @overload and @contextmanager. Trace the type-checking path for the overloaded implementation and add a regression test; done means the example produces no errors without regressing related overload checks.

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.