Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will be the benefits of type hinting in Python? [closed]

Tags:

python

types

pep

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?

like image 828
Deena Avatar asked Jul 06 '16 05:07

Deena


People also ask

What is the purpose of type hinting in Python?

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.

What is the purpose of type hinting?

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.

Does Python make hinting faster?

So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.

Is Python type hinting enforced?

Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.


1 Answers

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.
like image 51
All Іѕ Vаиітy Avatar answered Sep 29 '22 02:09

All Іѕ Vаиітy