[Python] typing.Union allows for callables as its type arguments

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

  1. Stack

    Stack Membro Participativo

    I am concerned about why callables are valid type arguments to pass to Union[] (as well as some other typing._GenericAlias objects)? What is the intended purpose of this?

    >>> def foo(): pass
    ...
    >>> Union[foo, print]
    typing.Union[foo, <built-in function print>]


    After some further investigation I found that, for some reason, the code in Python 3.7.0 stdlib does not match one located in typing GitHub repository. But typing module that my current Python installation uses allows callables explicitly:

    def _type_check(arg, msg, is_argument=True):
    <...>
    if not callable(arg):
    raise TypeError(f"{msg} Got {arg!r:.100}.")
    return arg

    Continue reading...

Compartilhe esta Página