📜  typehinting with when parameter has default - Python (1)

📅  最后修改于: 2023-12-03 14:48:04.465000             🧑  作者: Mango

Typehinting with default parameters in Python

When writing functions in Python, we often use default parameters to simplify our code. One issue with using default parameters, however, is that it can make typehinting more difficult. In this article, we’ll explore how to properly typehint functions with default parameters in Python.

The Problem

Consider the following function:

def greet(name: str = "world") -> str:
    return f"Hello, {name}!"

This function uses a default parameter to simplify the code. If no argument is provided, it defaults to "world". However, if we try to type hint this function, we run into a problem:

def greet(name: str = "world") -> str:
    return f"Hello, {name}!"

greet(123)  # This will not raise an error

The problem is that even though we’ve type hinted the name parameter as a str, we can still pass an integer as an argument and no error will be raised.

The Solution

To properly typehint a function with default parameters, we must use Union from the typing module. Union allows us to specify multiple types for a parameter or return value.

Here's how we can use Union to properly typehint the greet function:

from typing import Union

def greet(name: Union[str, int] = "world") -> str:
    return f"Hello, {name}!"

greet("Alice")  # This will work
greet(123)  # This will raise an error

In this example, we’ve used Union[str, int] to specify that the name parameter can be either a str or an int. Now, if we try to pass an argument that is not a str or int, an error will be raised.

Conclusion

When writing functions with default parameters in Python, it's important to properly type hint them to catch potential bugs. By using Union from the typing module, we can specify multiple types for a parameter or return value and ensure that our code is robust.