我正在阅读PEP 484 -- 类型提示
当它被实现时,该函数指定它接受和返回的参数类型。
def greeting(name: str) -> str:
return 'Hello ' + name
我的问题是,如果实现,使用 Python 进行类型提示有什么好处?
我在类型有用的地方使用了 TypeScript(因为 JavaScript 在类型识别方面有点愚蠢),而 Python 对类型有点智能,如果实现类型提示会给 Python 带来什么好处?这会提高python性能吗?
我正在阅读PEP 484 -- 类型提示
当它被实现时,该函数指定它接受和返回的参数类型。
def greeting(name: str) -> str:
return 'Hello ' + name
我的问题是,如果实现,使用 Python 进行类型提示有什么好处?
我在类型有用的地方使用了 TypeScript(因为 JavaScript 在类型识别方面有点愚蠢),而 Python 对类型有点智能,如果实现类型提示会给 Python 带来什么好处?这会提高python性能吗?
以类型化函数为例,
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仅在行执行后引发,您可以通过类型检查来避免这种情况。类型检查可让您从一开始就识别类型不匹配。
优点:
缺点:
Type hinting can help with:
I general lack of type hinting is also benefit:
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