Python 中Typing,你了解多少
Typing是一个功能强大的内置 Python 模块,它为类型提示提供运行时支持。可以强制 Python 在运行时进行类型检查。
在了解模块的作用 typing 之前,需要了解动态和静态类型的编程语言。
动态类型编程语言不需要参数、变量、返回变量等的类型规范。Python 是一种动态类型的编程语言;解释器在运行时配置类型。
静态类型编程语言确实需要参数、变量、返回变量等的类型规范。C、C++、C# 和 Java 是静态类型编程语言的一些示例。
通常,静态类型编程语言比动态类型编程语言更快,因为它们不需要在运行时配置类型。
不要误解类型和类型注释的作用。它们不会显著影响性能。没有必要仅将它们用于性能问题。
我将要展示的一些功能不需要键入模块,除非您的 Python 版本低于 3.12,并且某些功能确实需要 Python 3.12 或更高版本。
变量
变量类型提示的语法为 variable_name: type = value 。
number: int = 1234
string: str = "Hello world"
boolean: bool = True
decimal: float = 123.32
listOfInt: list[int] = [1, 2, 3, 4]
tupleOfbool: tuple[bool] = [True, False, True]
dictIntStr: dict[int, str] = {1: "Id1", 2: "Id2"}
# tuple of one int and one float
tuple [int, float] = (12, 23.4)
自定义类型
创建自定义类型别名就像定义变量类型一样简单。
Scalar = int
Vector = list[Scalar]
print(type(Scalar), type(Vector))
使用 TypeAlias 标记以明确表示这是一个类型别名,而不是普通的变量赋值
Scalar: TypeAlias = int
Vector: TypeAlias = list[float]
print(type(Scalar), type(Vector))
参数和返回值
参数的语法与变量的语法非常相似,对于 parameter_name: type 函数的 () 返回值, : 需要编写 -> return_value
Scalar: TypeAlias = int
Vector: TypeAlias = list[float]
def scale(scalar: float, vector: vector) -> Vector:
return [scalar * num for num in vector]
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector)
如果函数没有返回值(如果它是 void 函数),则使用 None 。
类型:Any
有时不想指定类型,或者需要在运行时更改它。出于这些目的,可以使用类型 Any .
from typing import Any
type_any: Any = None # as None
type_any = [] # as list
type_any = 2 # as int
print(s)
NewType
用于 NewType 创建不同的类型。
Password = NewType("Password", str)
some_password = Password("qwert")
静态类型检查器会将新类型视为原始类型的子类。这在帮助捕获逻辑错误方面非常有用:
def check_password(password: Password) -> bool:
...
# passes type checking
password1_check = check_password(UserId("qwerty"))
# fails type checking; an str is not a Password
password1_check = get_user_name("12345")
可以对类型执行 str 操作,而输出将是 str . Password 这还使您能够在需要 an str 的地方传递 Password 类型。
函数
用于 typing.Callable 指定需要作为函数分配的变量。
def add(a: int, b: int) -> int:
return a + b
a function that takes two parameters of type int and returns an int.
x: Callable[[int, int], int]
此语法必须与两个值一起使用:参数列表和返回类型。
如果给出一个文字省略 ... 号作为参数列表,则表示具有任意参数列表的可调用对象是可以接受的:
from typing import Callable
def add(a: int, b: int) -> int:
return a + b
x: Callable[..., int]
x = add
泛 型
一个函数或类,可以处理不同类型的 valeus,而不是单一类型。
def first[T](l: list[T]) -> T:
return l[0]
print(first[list[int]]([1, 2, 3])
print(first[list[float]]([1.0, 2.0, 3.0])
print(first[tuple[int]]((1, 2, 3))