python / python/mypy

Cryptic error message for two generic callables with different variable binding

Open
#17,551 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

If a @contextmanager yields a generic type alias, mypy 1.11 errors with Argument 1 to "contextmanager" has incompatible type "$TYPE"; expected "$TYPE" [arg-type], where the inferred and expected types are identical.

This does not happen if the generic type is inlined (no type alias), or if the type alias is not generic; see playground link below for examples.

This started happening in 1.11 (didn't happen in 1.10). This may be related to https://github.com/python/mypy/issues/8696, but I opened a new issue because it looks like a regression.

Real code that tripped this: link.

To Reproduce

Short version (more examples in playground links below):

GenericFn = Callable[[_T], _T]

@contextmanager
def make_generic() -> Iterator[GenericFn[_T]]:
    def rv(obj: _T) -> _T:
        return obj
    yield rv

Playground:

Expected Behavior

Either fail with a useful error message (the inferred and expected types being exactly the same is confusing; I am not sure what would fix the error), or don't fail (like 1.10).

Actual Behavior

error: Argument 1 to "contextmanager" has incompatible type "Callable[[], Iterator[Callable[[_T], _T]]]"; expected "Callable[[], Iterator[Callable[[_T], _T]]]"  [arg-type]

Your Environment

  • Mypy version used: 1.11.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12

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 minimal @contextmanager example with mypy 1.11.0 under Python 3.12 and --strict, then compare it with 1.10.1 and the linked playground cases. Trace the generic type-alias handling around make_generic and contextmanager; done means avoiding the regression or replacing the identical inferred and expected types with a useful error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.