Python Type Hints These are the slides for a recent 5 minute talk on Python Type Hints I gave at newhaven.io meetup. Slides are also available on Speaker Deck. PEP 3107 introduced syntax for function annotations, but the semantics were deliberately left undefined. There has now been enough 3rd party usage for static type analysis that the community would benefit from a standard vocabulary and baseline tools within the standard library. PEP 484 introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available. While these annotations are available at runtime through the annotations attribute… …no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and code generation utilizing type information. Of these goals, static analysis is the most important. This includes support for off-line type checkers, as well as providing a standard notation that can be used by IDEs for code completion and refactoring. integer of arbitrary size floating point number boolean value unicode string 8-bit string an arbitrary object list of str objects tuple of two int objects tuple of an arbitrary number of int objects dictionary from str keys to int values iterable object containing ints sequence of booleans dynamically typed value with an arbitrary type You can define new generic classes. Here is a very simple generic class that represents a stack. The Stack class can be used to represent a stack of any type Generic type variables can also be used to define generic functions. As with generic classes, the type variable can be replaced with any type. That means first can be used with any sequence type, and the return type is derived from the sequence item type. mypy is a static type checker for Python. If you sprinkle your code with type annotations, it can type check your code and find common bugs. As mypy is a static analyzer, your code’s type annotations are just hints and don’t interfere when running your program. You can install it with pip When you run your program with a standard Python interpreter, the annotations are treated primarily as comments. When we run mypy against our source code… …you’ll get useful errors before runtime. If you use Visual Studio Code, the Python extension has great support for mypy. Even though we now have typings, Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. Share this:Click to share on Twitter (Opens in new window)Click to share on Facebook (Opens in new window)