Return None from python function annotated with mypy, multiple return types

后端 未结 1 2030
野性不改
野性不改 2021-02-07 11:49

I come from a Typescript background. I\'m bringing static type checking into a python project I\'m working on (using mypy).

In Typescript, it is valid to return null fro

1条回答
  •  长情又很酷
    2021-02-07 12:40

    Okay, I found what I was missing in the documentation thanks to @zsol on the mypy gitter!

    Two helpful mypy features are the Optional and Union types that can be imported from python's typing module. Documentation here.

    If you want to annotate that the function can potentially return None in addition to the primary type, e.g. str, use Optional:

    from typing import Optional
    
    def test(flag: bool) -> Optional[str]:
        if flag:
            return 'success'
        else:
            return None
    

    If you want to annotate that the function can potentially return multiple types, e.g. str | bool, use Union:

    from typing import Union
    
    def test(flag: bool) -> Union[str, bool]:
        if flag:
            return 'success'
        else:
            return False
    

    0 讨论(0)
提交回复
热议问题