为什么在python3中未检查返回类型? [英] Why return type is not checked in python3?

查看:175
本文介绍了为什么在python3中未检查返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 PEP 484的示例

def greeting(name: str) -> str:
    return 'Hello ' + name

使用str调用函数的正确方法

Right way to call the function with str

>>> greeting("John")
'Hello John'

如果我用int调用它:

If I call it with int:

>>> greeting(2)
TypeError: must be str, not int

致电清单

>>> greeting(["John"])
TypeError: must be str, not list

一切正常,对吧? greeting函数始终接受str作为参数.

Everything works fine right? greeting function always accepts str as a parameter.

但是,例如,如果我尝试测试函数的返回类型,请使用相同的函数,但是将返回类型更改为int.

But if I try to test function return type, for example, use the same function but change return type to int.

def greeting(name: str) -> int:
    return 'Hello ' + name

函数返回str,但类型定义为int,并且不会引发异常:

Function returns str but type is defined as int, and no exception is raised:

>>> greeting("John")
'Hello John'

另一个例子:

def greeting(name: str) -> str:
    return len(name)

>>> greeting("John")
4

尽管PEP 484表示返回类型应为str,但实际上与上述示例中的参数类型检查并不相似.

Although PEP 484 says that return type is expected to be str, it is not actually analogical to argument type check which can be seen in above examples.

这表明name参数的预期类型为str. 以此类推,期望的回报类型为str.

This states that the expected type of the name argument is str. Analogically, the expected return type is str.

我是否缺少某些东西,或者没有类型检查返回类型?

Am I missing something or there is no type check for return type?

推荐答案

这个问题可能会使新手使用python3类型的提示有些混乱. python3中没有类型检查支持.这意味着,如果您在参数中传递了错误的类型,则python解释器将不会引发异常.

This question might cause a bit confusion for newcomers to python3 type hints. There is no type checking support in python3. This means that python interpreter will not raise an exception if you pass incorrect type in arguments.

mypy 可以用于您需要此功能的情况.

mypy can be used for in case you need this feature.

在上面的示例中提高TypeError的实际原因是(+)运算符的不安全使用. 如果您使用字符串格式更改示例中提供的功能

The actual reason for raising TypeError in examples above is unsafe use of (+) operator. If you change function provided in the examples using string formatting

def greeting(name: str) -> str:
    return 'Hello {}'.format(name)

上述所有情况都可以在不提高TypeError的情况下工作,并且在运行时不会进行类型检查.

All of the above cases will work without raising TypeError, and no type checking will happen during runtime.

类型提示由诸如PyCharm, PyCharm类型之类的IDE使用.提示,但这只是IDE显示的警告,而不是python解释器显示的警告.

Type Hinting is used by IDEs like PyCharm, PyCharm Type Hinting, but it is just warnings showed by IDE, not by python interpreter.

这篇关于为什么在python3中未检查返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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