📜  @typing.overload (1)

📅  最后修改于: 2023-12-03 15:13:11.835000             🧑  作者: Mango

@typing overloading

When writing a function, you might want to specify different function signatures for different parameter types. This can be achieved using the @typing.overload decorator, which is included in the typing module in Python.

How it works

The @typing.overload decorator allows you to define multiple function signatures for a single function name. The decorator is applied to the function definition and each overload is defined as a separate function using the same name.

from typing import overload

@overload
def foo(x: int) -> str:
    ...

@overload
def foo(x: str) -> int:
    ...

In this example, we define two overloads for a function called foo. The first overload takes an int as input and returns a str. The second overload takes a str as input and returns an int.

Type hints

The @typing.overload decorator is used in conjunction with type hints. Each overload is defined with its own type hint for the input parameters and return value. When a function is called, Python will attempt to match the input arguments to the correct function overload based on the type hints.

Example
from typing import overload

@overload
def square(x: int) -> int:
    ...

@overload
def square(x: float) -> float:
    ...

def square(x):
    return x * x

In this example, we define two overloads for a function called square. The first overload takes an int and returns an int. The second overload takes a float and returns a float. The final square function takes any input parameter and returns the square of that parameter.

Conclusion

The @typing.overload decorator is a powerful tool for defining multiple function signatures in Python. By using overloads, you can make your code more robust and easier to use, while also improving your code's readability and maintainability.