Python 3 and type hints - no so pink

There are number of cases where Python type checking simly doesn’t fly. Consider this data structure:

Foo = {"one": 1, "word": "hello"}

This dictionaries like taht are not really uncommon in Python programming.

A simplicity of creating free-form dictionaries helps to manage plenty of data manipulations, simple algorithms etc. An example can be object serialization to and from json format where you often end up processing such o data structures.

Python’s typing module provides a typing.Dict type for expressing expected argument an return value typen when they are about to be of a dictionary type. But that class allows for expressing expectation of a dictionary with exactly one type for all keys and exactly one type for all values. Our example cannot be described with it in other means than:

Dict [str, Any]

And that is a pretty weak type checking. We could easily come with examples of dictionaries that would “smuggle” nonsense here (also from a type perspective).

One may argue that in other statically typed languages it is not eve possible to create dictionary where values may have different types (being precise types that have no common base class like int and string). True. However, I feel like the example dictionary as above, due to specific nature of Python, is here rather a first-class citizen in many situations, while programming style i other OO languages will highly discourage you from creating dictionary of unspecified object value type.

One of the nice things about Python is that in many circumstances can achieve a lot without declaring small types for data item you are about to process, utilizing flexibilty of built-in types like tuples ans dictionaries, mixtures of both etc. Ype checking seems to favor explicit types to represent you business objects, for the purpose of being precise.

That’s my point for this short post. By starting to use type checking you give away something. Can’t eat cookie and have cookie. You either stay Pythonic or shift your programing style to something more close to how you program in Java C#, C++ etc.

comments powered by Disqus