How do I add default parameters to functions when using type hinting?
Type hints and default values in Python functions are combined as shown below:
Here, the parameter name
expects a str
, while message
uses a default value of "Hello"
if no argument is given. The function returns a type of None
.
Utilizing type hints in conjunction with default parameters can enhance the readability and maintainability of your Python functions, like decorating a Christmas tree π with functional and intricate ornaments.
Handling optional parameters
For scenarios where a parameter can be None
, use Optional
type hint from typing
module.
In this function, message
can either be a str
or None
. Within the function body, we ensure message
receives a valid string, either by parameter or by default.
Cautionary tales with mutable defaults
Using mutable defaults like lists or dictionaries can cause surprising results. This is since default values are evaluated only once when the function is defined, not each time it's called (a bit like remembering your ex's birthday π).
To avoid such unexpected behavior, use None
as a default and assign the mutable default inside the function:
When clarity favours unions over optionals
In situations where a parameter can accept None
or another type, for clear understanding over brevity, use Union
from typing
instead of Optional
.
The telltale sign(atu)res of clean code
Good function signatures can make reading code as smooth as silk. By smartly using type hinting and default values, your functions are self-documenting.
The Murphy's law of coding: foreseeing practical issues
Combining type hinting with default parameters does have its own challenges, especially around mutable default types. Like a ticking time bomb π£, these can explode if not handled with care. Leveraging typing
can be the bomb defusal kit in these situations.
Enforcing static typing: MyPy's got your back
With static typing enforcement tools like MyPy, your functions' type hints and default values not only reinforce your code's resilience, but also aid developers (or future you π΄) in quick comprehension of your code, as if every method had its own cheat sheet π.
Was this article helpful?