4.3 Type Hinting
Getting to Know Functions
Geeksforgeeks.org has a great article on Python docstrings, which are used to document functions and classes. It is a good idea to read it to understand how to write good documentation for your functions.
Type hinting with functions allows us to specify the expected data types of parameters and return values. This can help with code readability and debugging, as it makes it clear what types of values a function expects and what it will return.
Hinting Parameters
When defining a function, we can add type hints to the parameters by using a colon : followed by the expected data type. For example, if we have a function that takes an integer and a string as parameters, we can define it like this:
def my_function(param1: int, param2: str) -> None:
passHinting Return Values
We can also specify the return-type of a function using the -> syntax before the colon :. For example, if we have a function that returns an integer, we can define it like this:
def my_function() -> int:
return 42Python IDEs will recognize that the function is expected to return an integer, and they will provide appropriate suggestions and error checking if the return does not match the expected type.
Doc strings
We can also use type hinting to write documentation for our functions, which can be helpful for other developers (or ourselves in the future) to understand how to use the function correctly. To do this, we can simply include a doc string at the beginning of the function definition. A doc string is a string that describes what the function does, its parameters, and its return value. It is enclosed in triple quotes """ and can span multiple lines.
For instance, let’s create a function that will accept one parameter, an integer and return a boolean determining if the integer is even or not. We can use type hinting to specify the parameter and return types, and we can also include a doc string to explain what the function does:
def is_even(n: int) -> bool:
"""
Check if a number is even.
Args:
n (int): The number to check.
Returns:
bool: True if the number is even, False otherwise.
"""
return n % 2 == 0Doc strings do not have standard syntax. IDEs with Python tooling will use the string between triple quotes to provide context-aware suggestions and documentation while writing code. It allows us to leverage the power of IDEs for better code completion and understanding.
There are many conventions for doc strings. The example above is the Google style, which is one of the most popular. It is a good idea to follow a consistent style throughout your codebase. The doc string should be placed immediately after the function definition and should describe the function’s purpose, its parameters, and its return value. This will help other developers (and yourself) understand how to use the function correctly.