I. Scenarios of use
Python3 >= 3.5
When a function is defined with a prescribed input or output of a prescribed data type (i.e.Function Annotation
function annotation feature), which can only input or output the specifiedstatic data type . Then an error is reported if other types of data are passed in, as follows:
def test(name: str) -> str: return f"hello {name}" test(1) ... TypeError: must be str, not int
But this is a runtime error, which means that the problem is only discovered when the code is executed. Ideally, we should be able to find out if there is a problem as soon as we finish writing the code. Hence there are type checking tools, such as tools like mypy, and many IDEs that integrate such checking tools.
Then if you need to use the function and need to input or output theDynamic data types What to do, so overload is introduced.
II. Realization of a dynamic language
There are two more options for solving the above problem:
- 1. Use
- 2. Use
2.1 TypeVar
Let's start with the first one, for methods with a fixed number of parameters, the same parameter can be used this way if you intend to accept multiple types, let's say the parameter can be :int, float, str:
from typing import TypeVar T = TypeVar('T', int, float, str) def test(name: T) -> str: return f"hello {name}" test(2)
This scheme is more similar to the concept of interfaces in static languages, where you define a generic parent class, in which case you can pass subtypes over.
2.2 overload
Overload translates toheavy load (on a truck) In Java, there are two such concepts, override and overload. Overriding is actually rewriting the implementation logic while ensuring that the inputs and outputs remain unchanged. Overloading, on the other hand, allows modification of inputs and outputs, i.e., the same method name can support multiple types of inputs and outputs.
It's still very different from in a static language.
from typing import overload @overload def test(name: str) -> str: ... @overload def test(name: float) -> str: ... @overload def test(name: int, age: int) -> str: ... def test(name, age=18): return f"hello {name}" test(2)
By defining multiple functions with the same name, the above function with the same name needs to be decorated by overload decorator. You can see that the input type and output type of the decorated function can be changed.However, be sure to define a function of the same name without the decorator at the end It's the only way to achieve a dynamic effect.
What is the purpose of this use? There is an important sentence in the documentation.
“The @overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition, while the latter is used at runtime but should be ignored by a type checker. ”
Translation: functions that are decorated by overload are only meant to benefit from the type checking tool because they will be overridden by function definitions that are not decorated by overload, even though the undecorated function is for runtime use, but willIgnored by type checking tools 。
So, as you can see, overload is just for the checking tool. But if static type checking becomes part of the project, this will also avoid many problems, and you will have a better idea of what to do when writing code.
Supplement:
python
In Python, is a decorator used to define function overloading. Function overloading is the ability to define multiple functions in a class with the same name but different arguments, so that when a function is called, it can be executed with a different function depending on the arguments. This mechanism increases the readability and maintainability of the code. Since Python 3.5, modules have been introduced to support function overloading.
1. Why do we need function overloading?
Overloading of functions is a common programming technique in many programming languages. It allows us to use the same function name to perform different operations, depending on the type and number of arguments the function receives to determine exactly which function to perform. This makes the code more concise and easier to understand.
Suppose we have a function add that implements the operation of adding two numbers. Using function overloading, we can define multiple versions of the add function, each supporting different types of arguments. For example, we could define an add function for adding integers and another add function for adding floating point numbers.
2. Methods of use
Defining function overloading in Python using modules is very simple. We just need to use the @overload decorator above the function and the implementation of the @overload decorator below the function.
The following is an example of how to add integers and floating-point numbers by defining an add function:
from typing import overload @overload def add(a: int, b: int) -> int: pass @overload def add(a: float, b: float) -> float: pass def add(a, b): return a + b
In the above example, we first defined two function signatures using the @overload decorator to represent the addition of integers and the addition of floating point numbers. Then, a generic add function is implemented below the functions to handle different types of arguments. Note that in the generic function, we don't specify the parameter type and return type.
3. Practical applications of function overloading
Function overloading can be used in many scenarios, especially when we need to implement some functions with complex parameter types. Here are some examples of practical applications:
3.1 Data type conversion
Suppose we have a function to_str for converting variables of different types to strings. We can use function overloading to realize different conversion operations for different types of variables.
from typing import overload @overload def to_str(value: int) -> str: pass @overload def to_str(value: float) -> str: pass def to_str(value): return str(value)
3.2 Collection operations
Suppose we have a function union that is used to merge two collections. We can use function overloading to support different types of collection merging.
from typing import List, overload @overload def union(a: List[int], b: List[int]) -> List[int]: pass @overload def union(a: List[str], b: List[str]) -> List[str]: pass def union(a, b): return a + b
3.3 API Interface
Assuming we have a web request library, we can use function overloading to support different types of requests.
from typing import Dict, overload @overload def request(url: str, params: Dict[str, str]) -> str: pass @overload def request(url: str, data: bytes) -> bytes: pass def request(url, params_or_data): # Web requests implemented pass
4. Summary
Function overloading is a common programming technique that can be implemented in Python using modules. It improves code readability and maintainability, and also provides more flexibility in handling different types of arguments. In practice, function overloading can be used for data type conversions, collection operations, API interfaces, and more.
to this article on the use of Python module is introduced to this article, more related to the use of Python content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!