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?

Community
  • 1
  • 1
  • 3
    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. – salparadise Jul 06 '16 at 05:46
  • 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. – JL Peyret Jul 06 '16 at 06:01

1 Answers1

9

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

Chameleon
  • 9,722
  • 16
  • 65
  • 127