If you want to learn more about writing type hints and type-checking your Python code using third-party libraries, then you can refresh your memory in the Python Type Checking Guide.
Using Type Hints
Use Type Hints to Provide Automatic Type Information. As you may have noticed, in the docstrings you’ve written so far, you declared that the input variables should be of the type
float. However, the functions work just as well when you use integers.
But instead of doing so in your docstrings, you’ll use Python type hints to declare the argument and return types of your functions. First, you import
Union from the built-in
typing module, which allows you to specify multiple types for an argument.
Note that starting with Python 3.10, you can alternatively use the pipe operator (
|) as a type union alias, as seen on-screen. This more succinct syntax also allows you to remove the import statement from the top of your file.
However, to keep type hints more compatible with older versions of type-checking tools, you’ll stick with
Union in this example project. Adding type hints to your code allows you to use type checkers such as mypy to catch type-related errors that might otherwise go unnoticed.
01:50 Did you notice you’ve introduced some repeated information and inconsistencies regarding the types you’re mentioning in the docstring? Fortunately, mkdocstrings understands type hints and can infer typing from them.
Become a Member to join the conversation.