Home > Article > Backend Development > Best practices for type hints in Python
It’s great to use dynamic language for a while, and the code is reconstructed in the crematorium. I believe you must have heard this sentence. Like unit testing, although it takes a small amount of time to write code, it is very worthwhile in the long run. This article shares how to better understand and use Python's type hints.
Type hints (introduced since PEP 3107) are used to add variables, parameters, function parameters and their return values, class attributes and methods. type.
Python's variable types are dynamic and can be modified at runtime to add type hints to the code. It is only supported at the syntax level and has no impact on the running of the code. The Python interpreter will ignore it when running the code. Type hints.
Therefore, an intuitive function of type hints is to improve the readability of the code, making it easier for the caller to pass in/out parameters of the appropriate type, and facilitating code reconstruction.
Python’s built-in basic types can be used directly for type hints:
Type hint examples for variables:
a: int = 3 b: float = 2.4 c: bool = True d: list = ["A", "B", "C"] e: dict = {"x": "y"} f: set = {"a", "b", "c"} g: tuple = ("name", "age", "job")
Type hints for functions:
def add_numbers(x: type_x, y: type_y, z: type_z= 100) -> type_return: return x + y + z
here The type_x, type_y, type_z, type_return can be built-in basic types or custom types.
Type hint of class:
class Person: first_name: str = "John" last_name: str = "Does" age: int = 31
If there is such a piece of code:
x: int = 2 x = 3.5
There will be no errors when executing with the Python interpreter:
With the help of mypy, first install it with pip install mypy, and then mypy script.py:
For more mypy related information, please refer to the previous article mypy. This tool makes Python's type hints very practical.
If the interpreter does not enforce type hints, why write type hints? It's true that type hints don't change the way your code runs: Python is dynamically typed by nature, and that's unlikely to change. However, from a developer experience perspective, type hints have many benefits.
(1) Use type hints, especially in functions, to clarify parameter types and the type of results produced, which is very easy to read and understand.
(2) Type hints eliminate cognitive overhead and make code easier to read and debug. Given the types of inputs and outputs, you can easily infer the objects and how they are called.
(3) Type hints can improve the code editing experience. IDEs can rely on type checking to statically analyze your code and help detect potential errors (e.g., passing parameters of the wrong type, calling the wrong method, etc.). Additionally, autocompletion is provided for each variable based on type hints.
Type checking of IDE
Type checking of IDE
Auto-completion after IDE type checking
If you need a float type hint inside the list, this will not work:
def my_dummy_function(l: list[float]): return sum(l)
The standard library typing takes this problem into consideration, you can do this:
from typing import List def my_dummy_function(vector: List[float]): return sum(vector)
If you want to prompt such a type:
my_dict = {"name": "Somenzz", "job": "engineer"}
With the help of Dict, you You can define the type like this:
from typing import Dict my_dict_type = Dict[str, str] my_dict: my_dict_type = {"name": "Somenzz", "job": "engineer"}
What if you need to prompt for such a type?
d = {"name": "Somenzz", "interests": ["chess", "tennis"]}
With the help of TypedDict, you can do this:
TypedDict
Starting in Python 3.10, Union is replaced by | This means that Union[X, Y] is now equivalent to X|Y.
Union[X, Y] (or X | Y) means X or Y.
Suppose your function needs to read files from the cache directory and load the Torch model. This cache directory location can be a string value (such as /home/cache), or it can be a Path object from the Pathlib library, in which case the code is as follows:
def load_model(filename: str, cache_folder: Union[str, Path]): if isinstance(cache_folder, Path): cache_folder = str(cache_folder) model_path = os.join(filename, cache_folder) model = torch.load(model_path) return model
When you need to pass in a function as a parameter, the type hint of this parameter can be Callable.
from typing import Callable def sum_numbers(x: int, y: int) -> int: return x + y def foo(x: int, y: int, func: Callable) -> int: output = func(x, y) return output foo(1, 2, sum_numbers)
You can also specify a parameter list for such function parameters, which is really powerful:
Syntax:
Callable[[input_type_1, ...], return_type]
Example:
def foo(x: int, y: int, func: Callable[[int, int], int]) -> int: output = func(x, y) return output
当你传入的参数可以为任何类型的时候,就可以使用 Any
def bar(input: Any): ...
如果你的函数使用可选参数,具有默认值,那么你可以使用类型模块中的 Optional 类型。
from typing import Optional def foo(format_layout: Optional[bool] = True): ...
Sequence 类型的对象是可以被索引的任何东西:列表、元组、字符串、对象列表、元组列表的元组等。
from typing import Sequence def print_sequence_elements(sequence: Sequence[str]): for i, s in enumerate(s): print(f"item {i}: {s}"
Tuple 类型的工作方式与 List 类型略有不同,Tuple 需要指定每一个位置的类型:
from typing import Tuple t: Tuple[int, int, int] = (1, 2, 3)
如果你不关心元组中每个元素的类型,你可以继续使用内置类型 tuple。
t: tuple = (1, 2, 3, ["cat", "dog"], {"name": "John"})
类型提示在代码之上带来了额外的抽象层:它们有助于记录代码,澄清关于输入/输出的假设,并防止在顶部执行静态代码分析 (mypy) 时出现的隐蔽和错误。
The above is the detailed content of Best practices for type hints in Python. For more information, please follow other related articles on the PHP Chinese website!