Proper way hint '->' mutiple return type in python function

Viewed 75

I was writing a function that can return a string or None.

so if i wanna hint that with '->',

Is this the valid way of doing it

def get_context(arg: str) -> str or None:
     ...

should I use the str or None here or theres a better way of hinting?

1 Answers

Union should be used when something can be one of many types

from typing import Union

def get_context(arg: str) -> Union[str, None]:
    ...

typing.Optional can be used when the type is either None or something else for convenience

from typing import Optional

def get_context(arg: str) -> Optional[str]:
    ...
Related