For examples of projects using type hints, see cursive_re, black, our own Real Python Reader, and Mypy itself. Other code using your libraries needs these type hints to be properly type checked itself. In libraries that will be used by others, especially ones published on PyPI, type hints add a lot of value. Type hints add little value in short throwaway scripts. If you’re just beginning to learn Python, you can safely wait with type hints until you have more experience. Here are a few rules of thumb on whether to add types to your project: Therefore, you can start adding types to critical components, and continue as long as it adds value to you. Code without type hints will be ignored by the static type checker. This means that you can gradually introduce types into your code. Python supports the concept of gradual typing. Should you use static type checking in your own code? It’s not an all-or-nothing question. If you need to use the typing module, then the import time may be significant, especially in short scripts. Type hints introduce a slight penalty in start-up time. 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. Annotations were introduced in Python 3.0, and it’s possible to use type comments in Python 2.7. ![]() Even though it probably pays off in spending less time debugging, you will spend more time entering code. Type hints take developer time and effort to add. There are also some downside you should consider: Of course, static type checking is not all peaches and cream. ![]() 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. ![]() The act of writing type hints forces you to think about the types in your program. Type hints help you build and maintain a cleaner architecture. They make it much easier to statically reason about your code. This works, but as there is no standard for docstrings (despite PEP 257), they can’t be easily used for automatic checks. Traditionally, you would use docstrings if you wanted to document the expected types of a function’s arguments. Type hints help catch certain errors, as you saw in the previous lesson. Here are some of the advantages of type hints: In the previous lesson, you took a peek into what type checking in Python looks like. In this lesson, you’ll explore the pros and cons of type hints.
0 Comments
Leave a Reply. |