[Python] Mypy fails with overloads and literals

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to understand typing.overload and have applied it in a simple case where I want a function that takes input x: Literal["foo", "bar"] and returns the list [x].

    I'd like mypy to type the resulting list as list[Literal["foo"]] or list[Literal["bar"]] depending on the value of x.

    I know I could achieve this with a TypeVar, but I'd still like to understand why the code below fails with the following error:

    test.py:14: error: Overloaded function implementation cannot produce return type of signature 1
    test.py:14: error: Overloaded function implementation cannot produce return type of signature 2


    from typing import Literal, overload


    @overload
    def f(x: Literal["foo"]) -> list[Literal["foo"]]:
    ...


    @overload
    def f(x: Literal["bar"]) -> list[Literal["bar"]]:
    ...


    def f(x: Literal["foo", "bar"]) -> list[Literal["foo", "bar"]]:
    return [x]

    Continue reading...

Compartilhe esta Página