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?
PEP 484 introduced type hints — a way to make Python feel statically typed. While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime.
Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.
So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.
Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.
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:
Cons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With