问题
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?
回答1:
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.
回答2:
Type hinting can help with:
- Data validation and quality of code (you can do it with assert too).
- Speed of code if code with be compiled since some assumption can be taken and better memory management.
- Documentation code and readability.
I general lack of type hinting is also benefit:
- Much faster prototyping.
- 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.
- 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
来源:https://stackoverflow.com/questions/38216974/what-will-be-the-benefits-of-type-hinting-in-python