[Python] How to type-overload functions with multiple optional args?

Discussão em 'Python' iniciado por Stack, Abril 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function with multiple kwargs with defaults. One of them (in the middle somewhere) is a boolean toggle that controls the return type.

    I would like to create two overloads for this method with Literal[True/False] but keeping the default value.

    My idea was the following:

    from typing import overload, Literal

    @overload
    def x(a: int = 5, t: Literal[True] = True, b: int = 5) -> int: ...

    @overload
    def x(a: int = 5, t: Literal[False] = False, b: int = 5) -> str: ...

    def x(a: int = 5, t: bool = True, b: int = 5) -> int | str:
    if t:
    return 5
    return "asd"


    But mypy raises:


    error: Overloaded function signatures 1 and 2 overlap with incompatible return types
    ​

    I assume that is because x() will conflict.

    But I cannot remove the default = False value in the second overload since it is preceded by arg a with a default.

    How can I overload this properly such that

    • x() → int
    • x(t=True) → int
    • x(t=False) → str

    Continue reading...

Compartilhe esta Página