pythontypes

Possible to enforce type hints?


Is there any advantage to using the 'type hint' notation in python?

import sys
def parse(arg_line: int) -> str:
    print (arg_line) # passing a string, returning None

if __name__ == '__main__':
    parse(' '.join(sys.argv[1:]))

To me it seems like it complicates the syntax without providing any actual benefit (outside of perhaps within a development environment). Based on this:

  • Are there any plans for python to contain type constraints within the language itself?
  • What is the advantage of having a "type hint" ? Couldn't I just as easily throw that into the docstring or something?

I also don't see this much in the python codebase itself as far as I can tell -- most types are enforced manually, for example: argparse.py and any other files I've glanced at in https://github.com/python/cpython/blob/3.7/Lib/.


Solution

  • Are there any plans for python to contain type constraints within the language itself?

    Almost certainly not, and definitely not before the next major version (4.x).

    What is the advantage of having a "type hint" ? Couldn't I just as easily throw that into the docstring or something?

    Off the top of my head, consider the following:

    • Type hints can be verified with tooling like mypy.
    • Type hints can be used by IDEs and other tooling to give hints and tips. E.g., when you're calling a function and you've just written foo(, the IDE can pick up on the type hints and display a box nearby that shows foo(x: int, y: List[int]). The advantage to you as a developer is that you have exactly the information you need exposed to you and don't have to munge an entire docstring.
    • Type hints can be used by modules like functools.singledispatch or external libraries like multipledispatch to add additional type-related features (in this case, dispatching function calls based on name and type, not just name).