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

1

18

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?

Sisco answered 6/7, 2016 at 5:41 Comment(2)
From the same pep you linked "Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter" I would say its value is to have a build time syntax check, to avoid those dreaded runtime errors.Kellby
I remember seeing somewhere that one of the intents was tooling and frameworks. For example, a GUI framework might be able to check that an int entry field was set up to validate/allow only.Asberry
F
10

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

Fingering answered 6/7, 2016 at 5:58 Comment(2)
python TNumber = TypeVar("TNumber", int, float, complex) def f(x: TNumber) -> TNumber: return x * x Montcalm
The statement Speed of code if code with be compiled since some assumption can be taken and better memory management. is absolutely misleading. There has been no evidence of this and there have been multiple tests to verify the same. You can check this whole question out. Any minor optimisation made whatsoever has negligible impact under the hood.Cuirbouilli

© 2022 - 2024 — McMap. All rights reserved.