Home > Enterprise >  Python type hinting: how to handle long, optional return values going into a variable?
Python type hinting: how to handle long, optional return values going into a variable?

Time:03-05

Let's say I have a function:

def foo() -> Union[
    Optional[bool], Optional[int], Optional[str]
]:
    pass

How should I hint the variable that calls this function? It's so long, this seems wrong?

def bar() -> None:
    """
    Do something
    """
    baz: Union[
    Optional[bool], Optional[int], Optional[str] = foo()

CodePudding user response:

You can create the specific type

FooType = Optional[Union[bool, str, int]]

And then use it:

def foo() -> FooType:
    pass

def bar() -> None:
    baz: FooType = foo()
  • Related