python / python/mypy

Incompatible override when overriding non-overload with overload

Open
#12,379 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-inheritance topic-overloads
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import overload, Union

class A:
    def f(self, x: Union[int, str]) -> None: ...
    
class B(A):
    @overload
    def f(self, x: int) -> None: ...
    @overload
    def f(self, x: str) -> None: ...
    def f(self, x: Union[int, str]) -> None: ...

https://mypy-play.net/?mypy=latest&python=3.10&gist=37c2291afd7ddd170576b1de208ba77c

produces:

main.py:7: error: Signature of "f" incompatible with supertype "A"
main.py:7: note:      Superclass:
main.py:7: note:          def f(self, x: Union[int, str]) -> None
main.py:7: note:      Subclass:
main.py:7: note:          @overload
main.py:7: note:          def f(self, x: int) -> None
main.py:7: note:          @overload
main.py:7: note:          def f(self, x: str) -> None
Found 1 error in 1 file (checked 1 source file)

But as far as I can see this is safe. Mypy accepts a union as an argument to B.f:

arg: Union[int, str]
B().f(arg)

Of course, the overloads are useless in this toy example, but the error also comes up if you vary the return type in the overloads. This came up in python/typeshed#7510.

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 example in the linked mypy-play case and compare the diagnostics for A.f and B.f. Trace the override compatibility check for an overloaded subclass method versus a non-overloaded superclass method. Done means this safe override is accepted while incompatible overloads remain rejected.

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.