Python中的类型提示有什么好处?

Dee*_*ena 13 python types pep

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

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

def greeting(name: str) -> str:
    return 'Hello ' + name
Run Code Online (Sandbox Code Playgroud)

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

我使用TypeScript,其中类型很有用(因为JavaScript在类型识别方面有点愚蠢),而Python对类型有点聪明,如果实现,可以给Python带来哪些好处?这会改善python的性能吗?

All*_*ітy 9

举一个类型函数的例子,

def add1(x: int, y: int) -> int:
    return x + y
Run Code Online (Sandbox Code Playgroud)

和一般功能.

def add2(x,y):
    return x + y
Run Code Online (Sandbox Code Playgroud)

使用mypy进行类型检查 add1

add1("foo", "bar")
Run Code Online (Sandbox Code Playgroud)

会导致

error: Argument 1 to "add1" has incompatible type "str"; expected "int"
error: Argument 2 to "add2" has incompatible type "str"; expected "int"
Run Code Online (Sandbox Code Playgroud)

不同输入类型的输出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
Run Code Online (Sandbox Code Playgroud)

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

优点:

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

缺点:

  • 交易美女的Python代码.


Cha*_*eon 7

类型提示可以帮助:

  1. 数据验证和代码质量(你也可以使用assert).
  2. 代码的速度,如果代码有编译,因为可以采取一些假设和更好的内存管理.
  3. 文档代码和可读性.

我普遍缺乏类型提示也有好处:

  1. 更快的原型设计.
  2. 在大多数情况下缺乏需要类型提示 - 鸭子总是鸭子 - 做变量将表现得不像鸭子将是没有类型暗示的错误.
  3. 可读性 - 在大多数情况下,我们真的不需要任何类型提示.

我认为类型提示是可选的不是必需的,如Java,C++ - 过度优化会杀死创造力 - 我们真的不需要关注变量的类型,而是首先考虑算法 - 我个人认为更好地编写一行代码而不是4在Java中定义简单的函数:)

def f(x):
  return x * x
Run Code Online (Sandbox Code Playgroud)

代替

int f(int x) 
{
   return x * x
}

long f(long x) 
{
   return x * x
}

long long f(int long) 
{
   return x * x
}
Run Code Online (Sandbox Code Playgroud)

...或使用模板/泛型