Skip to content

Can't overload __add__ for subclass #1987

Closed
@gvanrossum

Description

@gvanrossum

Consider the following working code:

from typing import overload

class S:
    @overload
    def __add__(self, arg: 'A') -> 'S': ...
    @overload
    def __add__(self, arg: 'S') -> 'S': ...

class A(S):
    @overload
    def __add__(self, arg: 'A') -> 'A': ...
    @overload
    def __add__(self, arg: 'S') -> 'S': ...

Think of 'S' as 'str' and 'A' as 'ascii', a subclass used only for literals containing only ASCII characters. The idea is that adding ASCII to ASCII produces ASCII, but all other combinations produce just strings.

The subclass 'A' redefines the method __add__ to express this idea. This version of the code works. However, the base class contains redundant overloads: 'A' is a subclass of 'S' so the base class is equivalent to the following, which doesn't use overloads:

class S:
    def __add__(self, arg: 'S') -> 'S': ...

And here's the rub: with this definition of 'S', the definition of __add__ in 'A' (still using overloads) is rejected:

__tmp__.py:10: error: Signature of "__add__" incompatible with supertype "S"

(The error points to the first @overload, but it seems to apply to the entire set of overloads.)

Now here's the real rub: if I change __add__ consistently to method, the error goes away!

[UPDATE I can't repro this for __radd__ -- it seems unique to __add__.]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions