Want to add type annotation to a variable? Do refactoring!

Posted on Thu, 06 Oct 2016 in Python

There is the PEP 526 implemented in Python 3.6 that adds optional type annotations for variables. It's replacement for type comments. There is one pitfall: adding type annotations for local variables can hide problems with code.

Such annotations are made for robots, for automatic code checkers. And if you use it to increase code readability, you are in trouble. It must be your last weapon, not the first one.

If you think that an annotation makes the code better, try to discover that is the problem. In most cases it's one of two possible variants: either variable has complex type or value for this variable is unclear.

In the case with complex type, you can try to extract custom class or use namedtuple or something like this.

In the second case, try to split the function. Or rewrite it more clearly.

For example, I love using "map", "sorted", "filter", and other things from functool. Sometimes I write big constructions that transform a data beyond recognition.

Of course, if I add type annotation for the result variable, it makes code more clear. But I think better to split such constructions up into smaller, cleaner steps, and give that steps good reasonable names.

---
Got a question? Hit me on Twitter: avkorablev