[Python] Python type hinting for value that could also be a callable

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I was recently trying to design a function that takes an optional default argument -- either a value or a callable that returns a value.

    I wrote this method to do so:

    T = TypeVar("T")


    def default_example(default: T | Callable[[], T] | None) -> T:
    # stuff
    if default is not None:
    return default() if callable(default) else default
    # more stuff


    However, my type hinter (pylance) is understandably upset because the type T itself could also be callable and its return type is not bound. Is there a way to modify this function to achieve what I want (value or callable or none) without using overloads or bounding the type variable?

    Continue reading...

Compartilhe esta Página