Skip to content

Errors on @overload in supertype signatures #20418

@sveinse

Description

@sveinse

Bug Report

Given ABC A which have two implementations B and C. Method C.view() may return either B or C, depending on argument type. When using @overload to describe this, mypy complains with "Signature of "view" incompatible with supertype "A"". However, the type annotations provided by the overload works as expected.

To Reproduce

from __future__ import annotations
from abc import ABC, abstractmethod
from typing import overload, reveal_type

class A(ABC):
    @abstractmethod
    def view(self, x: int | None = None) -> A: ...

class B(A):
    def view(self, x: int | None = None) -> B:
        return B()

class C(A):
    @overload  # mypy complains: "Signature of "view" incompatible with supertype "A""
    def view(self, x: int) -> B: ...
    @overload
    def view(self, x: None = None) -> C: ...
    def view(self, x: int | None = None) -> B | C:
        if x is None:
            return C()
        else:
            return B()

# This works as expected when @overload is used
reveal_type(C().view(None))  # Revealed type is C
reveal_type(C().view(5))     # Revealed type is B

https://gist.github.com/mypy-play/00b068b5b6eeebbea6f9486dba468708

Actual Behavior

main.py:14: error: Signature of "view" incompatible with supertype "A"  [override]
main.py:14: note:      Superclass:
main.py:14: note:          def view(self, x: int | None = ...) -> A
main.py:14: note:      Subclass:
main.py:14: note:          @overload
main.py:14: note:          def view(self, x: int) -> B
main.py:14: note:          @overload
main.py:14: note:          def view(self, x: None = ...) -> C

Your Environment

  • Mypy version used: 1.19.0
  • Mypy command-line flags: Default args in gist
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions