[Python] How to type hint a Callable of a function with default arguments?

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to Type Hint the function bar, but I got the Too few arguments error when I run mypy.

    from typing import Callable, Optional

    def foo(arg: int = 123) -> float:
    return arg+0.1

    def bar(foo: Callable[[int], float], arg: Optional[int] = None) -> float:
    if arg:
    return foo(arg)
    return foo()

    print(bar(foo))
    print(bar(foo, 90))


    I have also tried:

    • Callable[[], float] (got Too many arguments error)
    • Callable[[Optional[int]], float] (got another error)

    So, how should I do the Type Hinting of the bar function?

    Continue reading...

Compartilhe esta Página