If this helped you, please share!

Python type hints: make code easier to read and check

Published December 1, 2017 in programming - 0 Comments

All python code is Python 3.5+.

In the Pandas data import posts, I’m using Python type hints. Type hinting is a fairly new feature in Python and has been provisionally accepted as a language feature. It is also a thought-provoking design feature for a dynamically typed language. Types are not enforced at runtime.

The type hints proposal is PEP 484. The proposal describes the syntax for type annotations and the primary intent, which is enabling static code analysis.

My first experience with Python type hints was with code that uses type hint annotations in function arguments and return types. Adding type hints made the syntax more complex, but once I got used to reading the type hint annotations, I began to see the advantages.

Here, it is obvious at a glance that my main function should take a string argument. Specifying that the function returns nothing might be a bit pedantic, but I like the completeness of the type signature since it feels closer to C++ and Java syntax:

def main(path: str) -> None:
    movies_metadata_df = pd.read_csv('{}/movies_metadata.csv'.format(path),
      dtype={'adult': 'bool', 'belongs_to_collection': object})

Using a static type checker like mypy in a CI pipeline is a useful sanity check (at writing time, pylint does not support PEP 484). Mypy can check code that uses a mix of type hints and basic Python syntax so that gradual adoption of type hinting won’t break a build. PyCharm, which is my preferred Python IDE also supports static type hint checking.

There should be real benefits to using type hinting in complex Python functions because any developer who uses the code will be able to understand the inputs and outputs more quickly. Type hinting when combined with a static type checker, unlike comments, don’t run the risk of becoming stale. It should also help clarify the intent of the function during the code design phase.

We may lose some of the flexibility and rapid prototyping capabilities of dynamic typed Python code, but I believe using type hinting results in better designed, more readable code.

Tags: python

No comments yet

Leave a Reply: