Python 3 type hinting for None?

后端 未结 3 735
-上瘾入骨i
-上瘾入骨i 2021-01-01 08:59
def foo(
        hello: str=\'world\', bar: str=None,
        another_string_or_None: str|????=None):
    pass

I\'m trying to set a type hint in Py

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 09:15

    I know this question is considered answered thanks to @mbdevpl, however, I've wanted to add that type(None) is how you get the actual for None type, this can be useful for example in an if statement check like:

    if isinstance(x_var, type(None)):
        pass
    

    and since python3.5, you can also use do Union of a bunch of types with None as shown here:

    x_var: typing.Union[str, None]
    y_var: typing.Union[Dict, List, None]
    

    this is equivalent to:

    x_var: typing.Optional[str]
    y_var: typing.Optional[typing.Union[Dict, List]]
    

提交回复
热议问题