Explain Codes LogoExplain Codes Logo

How do I add default parameters to functions when using type hinting?

python
type-hinting
default-parameters
mutable-defaults
Anton ShumikhinbyAnton ShumikhinΒ·Oct 15, 2024
⚑TLDR

Type hints and default values in Python functions are combined as shown below:

def greet(name: str, message: str = "Hello") -> None: print(f"{message}, {name}!")

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.

from typing import Optional def log(message: Optional[str] = None) -> None: # Because sometimes, a void speaks louder than words. if message is None: message = 'Default log message' print(message)

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 🎁).

def append_to_element(element, target_list: list = []): target_list.append(element) # The list loves to keep gifts! return target_list

To avoid such unexpected behavior, use None as a default and assign the mutable default inside the function:

def append_to_element(element, target_list: Optional[list] = None): if target_list is None: target_list = [] # Starting a fresh list. No past baggage, please. target_list.append(element) return target_list

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.

from typing import Union def set_position(new_position: Union[int, None] = None): pass # And, set! 🎬

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 πŸ“š.