|
The Python PEP 0484 approach, unchecked type hints, is strange, and probably a bad idea. There are good arguments for entirely dynamic typing, or entirely static typing, or optional static typing. Those have all been used successfully in other languages. But optional static typing without checking is new. (It may have been tried in some forgotten language, but it never made it into a mainstream one.)
This is likely to create bugs, rather than fix them. The type you see looking at the code may not be the type being used there. This will confuse maintenance programmers. Worse, the compiler itself can't rely on the type info for optimization purposes. This limits optimizations in PyPy. Type checking is supposed to be performed by third party programs. The syntax is backwards compatible, and this doesn't fit the language well. Forward references to types are handled via a really tacky kludge: "When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later." So, sometimes you write def foo(item: 'Tree'):
instead of def foo(item: Tree):
It's not stated in what scope 'Tree' is evaluated. So don't reuse type names.Some type info is in comments: with frobnicate() as foo: # type: int
# Here foo is an int
Also, Python is getting header files (called "stub" files), like C. In most modern languages, such as Go and Rust, that's all handled automatically by storing type info in the object files. But in future Python, that will be manual.There's function overloading, sort of. There's "@overload", but it doesn't really do anything at run time yet. This whole thing is a collection of hacks in search of an architecture. This is the messiest type system of any mainstream language. Well designed type systems are hard enough. This is not one of them. If this hadn't come from Python's little tin god, it would have been laughed out of the Python community. Stop him before he kills again. |
Stub files are not mandatory; type annotations can be in the same file as the code. This is perfectly legal, for example:
Stub files exist because the syntax support didn't exist in earlier versions of Python, so if you write a library that supports older versions of Python you ship a stub file rather than causing syntax errors for a subset of your users.