Do union types actually exist in python?

前端 未结 4 1701
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 02:30

Since python is dynamically typed, of course we can do something like this:

def f(x):
    return 2 if x else \"s\"

But is this the way pyth

4条回答
  •  忘掉有多难
    2020-12-10 03:07

    the type itself does not exist because Python is just a dynamically typed language, however, in newer Python versions, Union Type is an option for Type Hinting,

    from typing import Union,TypeVar
    
    T = TypeVar('T')
    def f(x: T) -> Union[str, None]:
        if x:
            return "x"
    

    you can use that to annotate your code, thus enabling IDE/Editor level syntax checking.

提交回复
热议问题