17

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

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

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

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

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

4

2 回答 2

15

以类型化函数为例,

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

和一般功能。

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

使用 mypy 进行类型检查add1

add1("foo", "bar")

会导致

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

上不同输入类型的输出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

请注意,这add2是一般情况。ATypeError仅在行执行后引发,您可以通过类型检查来避免这种情况。类型检查可让您从一开始就识别类型不匹配。

优点:

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

缺点:

  • 交易 Python 代码之美。
于 2016-07-06T06:48:50.890 回答
9

Type hinting can help with:

  1. Data validation and quality of code (you can do it with assert too).
  2. Speed of code if code with be compiled since some assumption can be taken and better memory management.
  3. Documentation code and readability.

I general lack of type hinting is also benefit:

  1. Much faster prototyping.
  2. Lack of need type hinting in the most cases - duck always duck - do it variable will behave not like duck will be errors without type hinting.
  3. Readability - really we not need any type hinting in the most cases.

I think that is good that type hinting is optional NOT REQUIRED like Java, C++ - over optimization kills creativity - we really not need focus on what type will be for variable but on algorithms first - I personally think that better write one line of code instead 4 to define simple function like in Java :)

def f(x):
  return x * x

Instead

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

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

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

... or use templates/generics

于 2016-07-06T05:58:26.933 回答