In this lesson, you’ll explore the pros and cons of type hints. In the previous lesson, you took a peek into what type checking in Python looks like. Here are some of the advantages of type hints:
-
Type hints help catch certain errors, as you saw in the previous lesson.
-
Type hints help document your code. Traditionally, you would use docstrings if you wanted to document the expected types of a function’s arguments. This works, but as there is no standard for docstrings (despite PEP 257), they can’t be easily used for automatic checks.
-
Type hints improve IDEs and linters. They make it much easier to statically reason about your code.
-
Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program. While the dynamic nature of Python is one of its great assets, being conscious about relying on duck typing, overloaded methods, or multiple return types is a good thing.
Of course, static type checking is not all peaches and cream. There are also some downside you should consider:
-
Type hints take developer time and effort to add. Even though it probably pays off in spending less time debugging, you will spend more time entering code.
-
Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it’s possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you’ll have a better experience doing type checks using Python 3.6 or even Python 3.7.
-
Type hints introduce a slight penalty in start-up time. If you need to use the
typing
module, then the import time may be significant, especially in short scripts.
Should you use static type checking in your own code? It’s not an all-or-nothing question. Python supports the concept of gradual typing. This means that you can gradually introduce types into your code. Code without type hints will be ignored by the static type checker. Therefore, you can start adding types to critical components, and continue as long as it adds value to you.