Python 中的类型提示有什么好处? [英] What will be the benefits of type hinting in Python?

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

问题描述

我正在阅读 PEP 484 -- 类型提示

当它被实现时,函数指定它接受和返回的参数类型.

def greeting(name: str) ->字符串:返回你好"+名字

我的问题是,如果实现,使用 Python 进行类型提示有什么好处?

我在类型有用的地方使用了 TypeScript(因为 JavaScript 在类型识别方面有点愚蠢),而 Python 对类型有点智能,如果实现类型提示可以给 Python 带来什么好处?这会提高python的性能吗?

解决方案

以类型化函数为例,

def add1(x: int, y: int) ->内部:返回 x + y

和一个通用函数.

def add2(x,y):返回 x + y

add1

上使用 mypy 进行类型检查

add1("foo", "bar")

会导致

错误:add1"的参数 1 具有不兼容的类型str";预期的int"错误:add2"的参数 2 具有不兼容的类型str";预期的int"

add2 上不同输入类型的输出,

<预><代码>>>>添加2(1,2)3>>>add2("foo","bar")'foobar'>>>add2(["foo"] ,['a', 'b'])['foo', 'a', 'b']>>>add2(("foo",) ,('a', 'b'))('foo', 'a', 'b')>>>添加2(1.2, 2)3.2>>>添加2(1.2, 2.3)3.5>>>add2("foo" ,['a', 'b'])回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 2 行,添加类型错误:无法连接str"和list"对象

请注意,add2 是通用的.TypeError 仅在执行该行后才会引发,您可以通过类型检查来避免这种情况.类型检查可让您在一开始就识别类型不匹配.

优点:

  • 更轻松的调试 == 节省时间
  • 减少手动类型检查
  • 更简单的文档

缺点:

  • 交易 Python 代码之美.

I was reading through the PEP 484 -- Type Hints

when it is implemented, the function specifies the type of arguments it accept and return.

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

My question is, What are the benefits of type hinting with Python if implemented?

I have used TypeScript where types are useful (as JavaScript is kinda foolish in terms of type identification), while Python being kinda intelligent with types, what benefits can type hinting bring to Python if implemented? Does this improve python performance?

解决方案

Take an example of the typed function,

def add1(x: int, y: int) -> int:
    return x + y

and a general function.

def add2(x,y):
    return x + y

Type checking with mypy on add1

add1("foo", "bar")

would result in

error: Argument 1 to "add1" has incompatible type "str"; expected "int"
error: Argument 2 to "add2" has incompatible type "str"; expected "int"

the outputs for the different input types on add2,

>>> add2(1,2)
3

>>> add2("foo" ,"bar")
'foobar'

>>> add2(["foo"] ,['a', 'b'])
['foo', 'a', 'b']

>>> add2(("foo",) ,('a', 'b'))
('foo', 'a', 'b')

>>> add2(1.2, 2)
3.2

>>> add2(1.2, 2.3)
3.5

>>> add2("foo" ,['a', 'b'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in add
TypeError: cannot concatenate 'str' and 'list' objects

Note that add2 is general. A TypeError is raised only after the line is executed, you can avoid this with type checking. Type checking lets you identify type mismatches at the very beginning.

Pros:

  • Easier debugging == time saved
  • Reduced manual type checking
  • Easier documentation

Cons:

  • Trading beauty of Python code.

这篇关于Python 中的类型提示有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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