Hello! In python, there is a type hint, but a code like this:

def add(a: int, b: int) -> int: return a + b add('hello', 'world') 

well done. I know that there are external utilities for type checking, but I don’t understand: why the syntax was added to the language, but there is no check from the box?

After all, external utilities can check without any additional syntax, why so actively such an idea began to be discussed only now.

Something seems to be no more difficult to parse:

 #: int, int -> int def add(a, b): return a + b #: [int] li = [1,2,3] 

In the same js there is a "strict mode", which can be turned on and off at will, it seems to me that this is much more logical. It is clear that they have different tasks, but the situations seem to be similar.

  • Maybe because the type hints are interested in the main IDE developers. Well, not even the developers, probably, but the sellers. - user239133

1 answer 1

Type hints introduced by PEP 484 . Keep on hand.

Why is the syntax added to the language, but there is no check from the box?

In general, any questions "why in language X there is no feature Y", in the absence of an explicit rejection of it, the answer is "not done yet, maybe someday."

But in PEP 484 there is a sentence very similar to a refusal to make it part of the language:

It should also be noted that it should not be a convention, even by convention.

It is also important to note that Python will remain a dynamically typed language, and its authors do not intend to ever make type hints mandatory, even if only by agreement.

Although this does not directly exclude the possibility of the appearance of optional checks in the standard library, this would be an essential step towards "static typing by agreement", which the authors of the language do not want.

Anyway, type hints should stabilize in the language before building such a large feature on them, as built-in checks. And this will not happen before Python 3.8 .


After all, external utilities can check without any additional syntax

Yes, but:

  • Each analyzer is forced to enter its own syntax for this. Perhaps someday different implementations would come to a common de facto standard. And you can make a "preventive standard" to eliminate other developments on the vine.
  • This syntax should make it difficult to write annotations that are incompatible with the code being described.
    • Comments are very easy to make incompatible with the code, so that this does not happen, additional checks of the code itself are needed . Parse the code in Python intelligently with the Python parser, and not create and maintain it a piece of the new one.
    • And if you force the Python parser to do this, you can integrate the syntax more tightly into the language, for example, specify the type of the argument directly next to it. What has already been done by annotations in PEP 3107 , but annotations gradually become only type hints and nothing else .