联合类型实际上存在于python中吗? [英] Do union types actually exist in python?

查看:147
本文介绍了联合类型实际上存在于python中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于python是动态类型的,因此我们当然可以执行以下操作:

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

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

但这是python实际使用的方式吗?换而言之,例如,联合类型是否在Racket中的意义上存在?还是只像这样使用它们:

But is this the way python was actually intended to be used? Or in other words, do union types exist in the sense they do in Racket for example? Or do we only use them like this:

def f(x):
    if x:
        return "s"

我们唯一需要的联盟"是无"?

where the only "union" we need is with None?

推荐答案

仅当您使用静态类型的语言时才需要进行联合键入,因为您需要声明一个对象可以返回多种类型之一(在您的情况下,intstr,或者在另一个示例中为strNoneType).

Union typing is only needed when you have a statically typed language, as you need to declare that an object can return one of multiple types (in your case an int or str, or in the other example str or NoneType).

Python仅处理 objects ,因此甚至不需要考虑联合类型". Python函数返回它们返回的内容,如果程序员想要为不同的结果返回不同的类型,那么这就是他们的选择.选择是架构选择,对Python解释器没有影响(因此这里没有要基准化"的东西).

Python deals in objects only, so there is never a need to even consider 'union types'. Python functions return what they return, if the programmer wants to return different types for different results then that's their choice. The choice is then an architecture choice, and makes no difference to the Python interpreter (so there is nothing to 'benchmark' here).

Python 3.5确实引入了用于创建可选类型提示的标准,并且该标准包括 Optional[...] 注释.

Python 3.5 does introduce a standard for creating optional type hints, and that standard includes Union[...] and Optional[...] annotations.

这篇关于联合类型实际上存在于python中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆