Skip to content

Method types not inherited when overriding overloaded method #10054

Closed as not planned

Description

When having an overloaded method in a base class, a subclass does not inherit the type annotations for the method. Minimal example:

class Base1:
    @overload
    def foo(self, x: int, is_str: Literal[True]) -> str: ...

    @overload
    def foo(self, x: int, is_str: Literal[False]) -> int: ...

    @abstractmethod
    def foo(self, x: int, is_str: bool) -> int | str: ...


class Sub1(Base1):
    @overload
    def foo(self, x, is_str: Literal[True]) -> str: ...

    @overload
    def foo(self, x, is_str: Literal[False]) -> int: ...

    @override
    def foo(self, x, is_str):
        return str(x) if is_str else x

Here Sub1.foo has signature def foo(self: Self@Sub1, x: Unknown, is_str: Unknown) -> (str | Unknown). Consider the following:

class Base2:
    @abstractmethod
    def foo(self, x: int, is_str: bool) -> int | str: ...


class Sub2(Base2):
    @override
    def foo(self, x, is_str):
        return str(x) if is_str else x

Here Sub2.foo has signature def foo(self: Self@Sub2, x: int, is_str: bool -> (str | int). I would expect the same signature in the first example, however the overload obfuscates the signature.

Pyright usage: integrated into Pylance
Pyright verison: 1.1.396

Activity

  1. erictraut commented on Mar 10, 2025

    @erictraut
    Collaborator

    Pyright is working as designed here.

    In general, you need to supply type annotations at each level of the hierarchy. Pyright will infer parameter types in some very specific cases — notably, where it is a simple (not polymorphic / overloaded) signature, the arity (number of parameters) and parameter names / kinds match exactly. In all other cases, you need to provide annotations in the derived class methods. This limited inference behavior was implemented to provide better language server behaviors in pylance for untyped code bases. If you're interested in type checking (i.e. you are using pyright and have type checking enabled), you should provide type annotations for your methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedNot a bug, working as intendedbugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions