当前位置: 首页 > news >正文

Type Hints in Python:python的类型注释

个人博客:Sekyoro的博客小屋
个人网站:Proanimer的个人网站

Python中的类型系统,使用type hints使得整个开发过程更加顺畅.类似typescript的目的.

Type Theory

值得一提的是python目前还在蒸蒸日上,所以一些东西后面可能会有些改变,不过答题的东西是不变的,可以使用mypypython/mypy: Optional static typing for Python (github.com)(或者pyrightmicrosoft/pyright: Static Type Checker for Python (github.com))进行检查,可以使用Welcome to Pydantic - Pydantic作为数据验证,大多数IDE本身也对这个默认支持.

PEP 483 是这一切的起点.

Subtypes

一个重要的概念是subtypes(亚型)。

形式上,如果以下两个条件成立,我们说T型是U的subtypes:

  • 来自T的每个值也在U类型的值集合中。
  • 来自U型的每个函数也在T型函数的集合中。

这两个条件保证了即使类型T与U不同,类型T的变量也可以总是假装为U。

举个具体的例子,考虑T=bool和U=int。bool类型只取两个值。通常这些名称表示为True和False,但这些名称分别只是整数值1和0的别名:

Covariant, Contravariant, and Invariant

在复合类型中使用子类型时会发生什么?例如,Tuple[bool]是Tuple[int]的一个子类型吗?答案取决于复合类型,以及该类型是协变(Covariant)的、反变(Contravariant)的还是不变(Invariant)的。

  • 元组是协变(Covariant)的。这意味着它保留了其项类型的类型层次结构:Tuple[bool]是Tuple[int]的子类型,因为bool是int的子类型。
  • 列表是不变(Invariant)的。不变类型不能保证子类型。虽然List[bool]的所有值都是List[int]的值,但您可以将int附加到List[int],而不是List[bool。换句话说,子类型的第二个条件不成立,并且List[bool]不是List[int]的子类型。
  • Callable在其参数中是反变(Contravariant)的。这意味着它颠倒了类型层次结构。若Callable[[T],…]作为一个函数,它唯一的参数是T类型。Callable的一个例子[[int],…]是double()函数。反变意味着,如果期望一个在布尔上操作的函数,那么一个在int上操作的功能是可以接受的。

内置类型

x: int = 1
x: float = 1.0
x: bool = True
x: str = "test"
x: bytes = b"test"

在3.8及之前,使用from typing import List,Dict,Set,Tuple 来使用collections,之后可以直接使用list,dict这种.

x: list[int] = []
x: tuple[int,...] = (1, 2)
x: set[int] = {1, 2}
x: dict[str, float] = {"field": 2.0, "field2": "a"}

在3.10+,可以直接使用|代替Union

x: list[int|str] = [1, 2, "a"]
x: Optional[str]

函数

x: Callable[[int], str] = stringify
def gen(n: int) -> Iterator[int]:for i in range(n):yield idef send_email(address: Union[str,list[str],None]) -> None:...
# This says each positional arg and each keyword arg is a "str"
def call(self, *args: str, **kwargs: str) -> str:reveal_type(args)  # Revealed type is "tuple[str, ...]"reveal_type(kwargs)  # Revealed type is "dict[str, str]"request = make_request(*args, **kwargs)return self.do_api_query(request)
def quux(x: int,/, y: str, z: float) -> None:...quux(1, '2', z=3.0)

如果你想要函数的调用者在某个参数位置只能使用位置参数而不能使用关键字参数传参,那么你只需要在所需位置后面放置一个/。

如果你希望强迫调用者使用某些参数,且必须以关键字参数的形式传参,那么你只需要在所需位置的前一个位置放置一个*。

from typing import ClassVarclass BankAccount:account_name: strbalance: floatcount: ClassVardef __init__(self, account_name: str, initial_balance: float = 0.0) -> None:self.account_name = account_nameself.balance = initial_balancedef deposit(self, amount: float) -> None:self.balance += amountdef withdraw(self, amount: float) -> None:self.balance -= amount
class AuditedBankAccount(BankAccount):audit_log: list[str]def __init__(self, account_name: str, initial_balance: float = 0.0) -> None:super().__init__(account_name, initial_balance)self.audit_log = []def deposit(self, amount: float) -> None:self.audit_log.append(f"Deposited {amount}")def withdraw(self, amount: float) -> None:self.audit_log.append(f"Withdrew {amount}")# You can use the ClassVar annotation to declare a class variable
class Car:seats: ClassVar[int] = 4passengers: ClassVar[list[str]]class A:def __setattr__(self, key, value):print("Setting", key, "to", value)self.__dict__[key] = valuedef __getattr__(self, key):print("Getting", key)return self.__dict__[key]class Person(A):name: strage: intweight: floatdef __init__(self, name: str, age: int, weight: float) -> None:self.name = nameself.age = ageself.weight = weightp = Person("John", 30, 80.0)
print(p.name)

Forward references

# You may want to reference a class before it is defined.
# This is known as a "forward reference".
def f(foo: A) -> int:  # This will fail at runtime with 'A' is not defined...# However, if you add the following special import:
from __future__ import annotations
# It will work at runtime and type checking will succeed as long as there
# is a class of that name later on in the file
def f(foo: A) -> int:  # Ok...# Another option is to just put the type in quotes
def f(foo: 'A') -> int:  # Also ok...class A:# This can also come up if you need to reference a class in a type# annotation inside the definition of that class@classmethoddef create(cls) -> A:...

Decorators

decorator通常是将一个函数作为参数并返回另一个函数的函数。

用类型来描述这种行为可能有点棘手;我们将展示如何使用TypeVar和一种称为参数规范的特殊类型变量来实现这一点。

假设我们有装饰器,尚未进行类型注释,它保留了原始函数的签名,只打印装饰函数的名称:

def printing_decorator(func):def wrapper(*args, **kwds):print("Calling", func)return func(*args, **kwds)return wrapper

给这个装饰器类型注释

from functools import wraps
from typing import TypeVar, Callable, cast, Any
F = TypeVar("F", bound=Callable[..., Any])
def printing_decorator(func: F) -> F:@wraps(func)def wrapper(*args: Any, **kwargs: Any) -> Any:print("Calling", func.__name__)return func(*args, **kwargs)return cast(F, wrapper)

这仍然存在一些不足。首先,我们需要使用不安全的cast()来说服mypy wrapper()与func具有相同的签名。其次,wrapper()函数没有经过严格的类型检查,尽管wrapper函数通常足够小,所以这不是什么大问题。

from typing import Callable, TypeVar
from typing_extensions import ParamSpecP = ParamSpec('P')
T = TypeVar('T')def printing_decorator(func: Callable[P, T]) -> Callable[P, T]:def wrapper(*args: P.args, **kwds: P.kwargs) -> T:print("Calling", func)return func(*args, **kwds)return wrapper

可以使用参数规范(ParamSpec)来获得更好的类型注释:

from typing import TypeVar, Callable, Any,ParamSpec
P = ParamSpec("P")
T = TypeVar('T')
def printing_decorator(func: Callable[P,T]) -> Callable[P,T]:@wraps(func)def wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:print("Calling", func.__name__)return func(*args, **kwargs)return wrapper

参数规范还允许描述更改输入函数签名的装饰器

from typing import Callable, TypeVar
from typing_extensions import Concatenate, ParamSpecP = ParamSpec('P')
T = TypeVar('T')# We reuse 'P' in the return type, but replace 'T' with 'str'
def stringify(func: Callable[P, T]) -> Callable[P, str]:def wrapper(*args: P.args, **kwds: P.kwargs) -> str:return str(func(*args, **kwds))return wrapper@stringifydef add_forty_two(value: int) -> int:return value + 42a = add_forty_two(3)reveal_type(a)      # Revealed type is "builtins.str"add_forty_two('x')  # error: Argument 1 to "add_forty_two" has incompatible type "str"; expected "int"P = ParamSpec('P')
T = TypeVar('T')def printing_decorator(func: Callable[P, T]) -> Callable[Concatenate[str, P], T]:def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T:print("Calling", func, "with", msg)return func(*args, **kwds)return wrapper@printing_decorator
def add_forty_two(value: int) -> int:return value + 42a = add_forty_two('three', 3)
from typing import Any, Callable, TypeVarF = TypeVar('F', bound=Callable[..., Any])def bare_decorator(func: F) -> F:...def decorator_args(url: str) -> Callable[[F], F]:...

Generics

内置集合类是泛型类。泛型类型有一个或多个类型参数,这些参数可以是任意类型。例如,dict[int,str]具有类型参数int和str,list[int]具有类型形参int。

from typing import TypeVar, GenericT = TypeVar('T')class Stack(Generic[T]):def __init__(self) -> None:# Create an empty list with items of type Tself.items: list[T] = []def push(self, item: T) -> None:self.items.append(item)def pop(self) -> T:return self.items.pop()def empty(self) -> bool:return not self.items

类ClassName(Protocol[T])被允许作为类ClassName的简写class ClassName(Protocol, Generic[T])

TypedDict

Python程序经常使用带有字符串键的字典来表示对象。TypedDict允许您为表示具有固定架构的对象的字典提供精确的类型,例如{‘id’:1,‘items’:〔‘x’〕}。

from typing import TypedDict
Movie = TypedDict('Movie', {'name': str, 'year': int})movie: Movie = {'name': 'Blade Runner', 'year': 1982}
class Movie(TypedDict):name: stryear: intclass BookBasedMovie(Movie):based_on: str

Literal

Literal类型可以指示表达式等于某个特定的primitive 值。

例如,如果我们用Literal[“foo”]类型注释一个变量,mypy将理解该变量不仅是str类型的,而且具体地等于字符串“foo”。

from typing import Final, Literaldef expects_literal(x: Literal[19]) -> None: passreveal_type(19)
expects_literal(19)

更多类型

  • NoReturn可以告诉mypy函数永远不会正常返回。
  • NewType允许您定义类型的变体,该变体被mypy视为单独的类型,但在运行时与原始类型相同。例如,您可以将UserId作为int的一个变体,它在运行时只是一个int。
  • @overload允许您定义一个可以接受多个不同签名的函数。如果您需要对难以正常表达的参数和返回类型之间的关系进行编码,这将非常有用。
  • Async 类型允许您使用异步和等待来键入检查程序。
from typing import NoReturndef stop() -> NoReturn:raise Exception('no way')from typing import NewTypeUserId = NewType('UserId', int)def name_by_id(user_id: UserId) -> str:...UserId('user')          # Fails type checkname_by_id(42)          # Fails type check
name_by_id(UserId(42))  # OKnum: int = UserId(5) + 1

参考

  1. Python Type Checking (Guide) – Real Python
  2. Type hints cheat sheet - mypy 1.7.1 documentation
  3. https://python-type-challenges.zeabur.app/

如有疑问,欢迎各位交流!

服务器配置
宝塔:宝塔服务器面板,一键全能部署及管理
云服务器:阿里云服务器
Vultr服务器
GPU服务器:Vast.ai

相关文章:

  • VIVADO 擦除flash
  • 在Linux本地部署开源自托管导航页配置服务Dashy并远程访问
  • 计算机组成原理-Cache替换算法
  • 【华为OD题库-048】拔河比赛-java
  • Docker+ Jenkins+Maven+git自动化部署
  • 每日一题:LeetCode-283. 移动零
  • 在Django中使用Q对象和条件运算符来构建动态查询
  • DDoS高防IP到底是什么?
  • C# 友元程序集
  • 225. 用队列实现栈 --力扣 --JAVA
  • linux下实现Qt程序实现开机自启动
  • LeetCode [简单](非递归)二叉树的中序遍历
  • Python爬虫遇到重定向URL问题时如何解决?
  • [密码学]DES
  • 【九日集训】第五天:排序
  • 〔开发系列〕一次关于小程序开发的深度总结
  • Angular2开发踩坑系列-生产环境编译
  • CODING 缺陷管理功能正式开始公测
  • CSS实用技巧
  • ES6 学习笔记(一)let,const和解构赋值
  • EventListener原理
  • Hibernate最全面试题
  • HTML中设置input等文本框为不可操作
  • js作用域和this的理解
  • Python_网络编程
  • react 代码优化(一) ——事件处理
  • Redux系列x:源码分析
  • Spring核心 Bean的高级装配
  • vue-router的history模式发布配置
  • 阿里云购买磁盘后挂载
  • 多线程 start 和 run 方法到底有什么区别?
  • 浮现式设计
  • 简单易用的leetcode开发测试工具(npm)
  • 如何优雅的使用vue+Dcloud(Hbuild)开发混合app
  • 再次简单明了总结flex布局,一看就懂...
  • 找一份好的前端工作,起点很重要
  • 智能合约开发环境搭建及Hello World合约
  • LevelDB 入门 —— 全面了解 LevelDB 的功能特性
  • 树莓派用上kodexplorer也能玩成私有网盘
  • #我与Java虚拟机的故事#连载11: JVM学习之路
  • (+4)2.2UML建模图
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (3)nginx 配置(nginx.conf)
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (考研湖科大教书匠计算机网络)第一章概述-第五节1:计算机网络体系结构之分层思想和举例
  • (三)Honghu Cloud云架构一定时调度平台
  • (十五)使用Nexus创建Maven私服
  • (四) Graphivz 颜色选择
  • (一)C语言之入门:使用Visual Studio Community 2022运行hello world
  • (原+转)Ubuntu16.04软件中心闪退及wifi消失
  • .cfg\.dat\.mak(持续补充)
  • .NET 2.0中新增的一些TryGet,TryParse等方法
  • .net core 6 集成和使用 mongodb
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)