#๐Ÿ”’ Mypy: Overloaded function signatures 1 and 2 overlap with incompatible return types

8 messages ยท Page 1 of 1 (latest)

kind sapphire
#

I have a function that will return a single response as an int if the count passed to the function is 1. Elsewise, a list of responses is returned.

I tried to type this using overloads, however I get an error from MyPy: Overloaded function signatures 1 and 2 overlap with incompatible return types [overload-overlap]

I've researched, and it seems like the problem is that a count of 1 would satisfy both overloads, which is not allowed.

Does anyone know how to get around this?

@overload
def read_and_check(self, address: int, count: Literal[1] = 1) -> int: ...

@overload
def read_and_check(self, address: int, count: int) -> list[int]: ...
sour pineBOT
#

@kind sapphire

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

zinc peak
#

have you made the actual implementation?

    @overload
    def read_and_check(self, address: int, count: Literal[1] = 1) -> int: ...
    @overload
    def read_and_check(self, address: int, count: int) -> list[int]: ...
    def read_and_check(self, address: int, count: int = 1):
        """actual implementation"""
        ...
kind sapphire
# zinc peak have you made the actual implementation? ```py @overload def read_and_ch...

Yes, just forgot to put it here...

Here is a working example:

from typing import Literal, overload


@overload
def read_and_check(address: int, count: Literal[1] = 1) -> int: ...


@overload
def read_and_check(address: int, count: int) -> list[int]: ...


def read_and_check(address: int, count: int = 1) -> int | list[int]:
    """actual implementation"""
    if count == 1:
        return 1
    else:
        return [1, 2, 3]
#

Curiously, this is fine with Pyright

#

But MyPy gives the same error.

sour pineBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.