python / python/mypy

mypy incorrectly reports incompatible return types for overloaded methods

Open
#12,733 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

@overload
def foo(cls: type[dict], mapping: SupportsKeysAndGetItem[K, V], /) -> dict[K, V]: ...
@overload
def foo(cls: type[dict], mapping: SupportsKeysAndGetItem[str, V], /, **kwargs: V) -> dict[str, V]: ...

Return types are compatible.

class FrozendictBase(Generic[K, V]):
    @overload
    def __new__(
            cls,
            mapping: SupportsKeysAndGetItem[K, V],
            /,
            ) -> 'FrozendictBase[K, V]': ...

    @overload
    def __new__(
            cls,
            mapping: SupportsKeysAndGetItem[str, V],
            /,
            **kwargs: V,
            ) -> 'FrozendictBase[str, V]': ...

Return types are also compatible, but mypy reports an error.

To Reproduce

  1. Download file.txt and save as sandbox.py.
  2. Run mypy sandbox.py.

Expected Behavior

sandbox.py:8: error: Invariant type variable "V" used in protocol where covariant one is expected

This is due to #5775.

Actual Behavior

sandbox.py:8: error: Invariant type variable "V" used in protocol where covariant one is expected
sandbox.py:39: error: Overloaded function signatures 3 and 4 overlap with incompatible return types
sandbox.py:54: error: Overloaded function signatures 5 and 6 overlap with incompatible return types

Your Environment

  • Mypy version used: mypy 0.950
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.10.4
  • Operating system and version: Windows 10

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

Download the linked file and save it as sandbox.py, then run mypy sandbox.py to reproduce the overload diagnostics. Investigate the incompatible return-type reports for overloaded signatures 3/4 and 5/6; done means those reports no longer appear while the expected invariant-type-variable error remains.

Written by the indexing model from the issue text.

Assessment

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