python内置模块typing 类型提示

2023-10-22 07:44

本文主要是介绍python内置模块typing 类型提示,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、简介

typing 是 Python 标准库中的一个模块,用于支持类型提示(Type Hints)。类型提示是一种在代码中指定变量、函数参数和返回值的类型的方法,它可以提供代码的可读性、可维护性和工具支持。

二、常用类型及示例
  1. Any:表示任意类型。
    from typing import Anytest:Any = 2def process_data(data: Any) -> None:# 对任意类型的数据进行处理pass
    
  2. List:表示列表类型。
    from typing import Listtest: List[int] = [2]def process_list(items: List[int]) -> None:# 处理整数列表pass
    
  3. Tuple:表示元组类型。
    from typing import Tupletest:Tuple[int] = (2,)def process_tuple(data: Tuple[str, int]) -> None:# 处理包含字符串和整数的元组pass
    
  4. Dict:表示字典类型。
    from typing import Dicttest:Dict[str,int] = {"key":1}def process_dict(data: Dict[str, int]) -> None:# 处理键为字符串,值为整数的字典pass
    
  5. Set:表示集合类型。
    from typing import Settest: Set[int] = {2,3}def process_set(data: Set[str]) -> None:# 处理字符串集合pass
    
  6. Union:表示多个可能的类型。
    from typing import Uniontest:Union[int,str] = 2def process_data(data: Union[int, float]) -> None:# 处理整数或浮点数pass
    
  7. Optional:表示可选类型,即可以是指定类型或者 None。
    from typing import Optionaltest:Optional[int] = Nonedef process_data(data: Optional[str]) -> None:# 处理可选的字符串,可以为 Nonepass
    
  8. Callable:表示可调用对象的类型。
    from typing import Callabledef test(nu1: int, nu2: int) -> int:print('test')return nu1+nu2def process_function(func: Callable[[int, int], int]) -> None:# 处理接受两个整数参数并返回整数的函数print(func(2,2))process_function(test)
    
  9. Iterator:表示迭代器类型。
    from typing import Iteratortest:Iterator[int] = iter([2])def process_iterator(data: Iterator[int]) -> None:# 处理整数迭代器pass
    
  10. Generator:表示生成器类型。
    from typing import Generatordef generate_numbers() -> Generator[int, None, None]:yield 1yield 2test: Generator[int, None, None] = generate_numbers()
    
  11. Iterable:表示可迭代对象的类型。
    from typing import Iterabletest:Iterable[str] = ["apple", "banana", "cherry"]tes1:Iterable[str] = ("apple", "banana", "cherry")def process_iterable(data: Iterable[str]) -> None:# 处理可迭代的字符串对象pass
    
  12. Mapping:表示映射类型。
    from typing import Mappingtest:Mapping[str,int] = {"apple": 1, "banana": 2, "cherry": 3}def process_mapping(data: Mapping[str, int]) -> None:# 处理键为字符串,值为整数的映射对象pass
    
  13. Sequence:表示序列类型。
    from typing import Sequencetest: Sequence[int] = [1, 2, 3, 4, 5]def process_sequence(data: Sequence[int]) -> None:# 处理整数序列pass
    
  14. AnyStr:表示任意字符串类型。
    from typing import AnyStrstr:AnyStr = '213'
    
  15. NoReturn:表示函数没有返回值。
    from typing import NoReturndef my_func() -> NoReturn:print("This function does not return anything")my_func()
    
  16. FrozenSet: 表示不可变的集合类型。类似于 Set,但不能进行修改。
    from typing import FrozenSetdef process_data(data: FrozenSet[str]) -> None:for item in data:print(item)test: FrozenSet[str] = frozenset(["apple", "banana", "orange"])process_data(test)
    
  17. Literal: 表示字面值类型。用于指定变量的取值范围,只能是指定的字面值之一
    from typing import Literaldef process_color(color: Literal["red", "green", "blue"]) -> None:print("Selected color:", color)process_color("red")
    process_color("green")
    process_color("blue")
    
  18. AsyncGenerator: 表示异步生成器类型。类似于 Generator,但用于异步上下文中生成值的类型
    from typing import AsyncGenerator
    import asyncioasync def generate_data() -> AsyncGenerator[int, str]:yield 1yield 2yield 3async def process_data() -> None:async for num in generate_data():print("Received:", num)asyncio.run(process_data())
    
  19. ContextManager: 表示上下文管理器类型。用于定义支持 with 语句的对象的类型
    from typing import ContextManagerclass MyContextManager:def __enter__(self):print("Entering context")def __exit__(self, exc_type, exc_value, traceback):print("Exiting context")def process_data(manager: ContextManager) -> None:with manager:print("Processing data")process_data(MyContextManager())
    
  20. AsyncIterator: 表示异步迭代器类型。类似于 Iterator,但用于异步上下文中进行迭代的类型
    from typing import AsyncIterator
    import asyncioasync def async_range(n: int) -> AsyncIterator[int]:for i in range(n):yield iawait asyncio.sleep(1)async def process_data() -> None:async for num in async_range(5):print("Received:", num)asyncio.run(process_data())
  21. Annotated: 用于添加类型注解的装饰器。可以在类型提示中添加额外的元数据信息
    from typing import Annotateddef process_data(data: Annotated[str, "user input"]) -> None:print("Received data:", data)process_data("Hello")
    
  22. AbstractSet: 表示抽象集合类型。是 Set 的基类,用于指定集合的抽象接口。通常用作父类或类型注解
    from typing import AbstractSetdef process_data(data: AbstractSet[str]) -> None:for item in data:print(item)my_set: AbstractSet[str] = {"apple", "banana", "orange"}
    process_data(my_set)
    
  23. Awaitable: 表示可等待对象的类型。用于指定可以使用 await 关键字等待的对象的类型。
from typing import Awaitable
import asyncioasync def async_task() -> int:await asyncio.sleep(1)return 42async def process_task(task: Awaitable[int]) -> None:result = await taskprint("Task result:", result)asyncio.run(process_task(async_task()))
  1. AsyncIterable: 表示异步可迭代对象的类型。类似于 Iterable,但用于异步上下文中进行迭代的类型。
    from typing import AsyncIterable
    import asyncioasync def async_range(n: int) -> AsyncIterable[int]:for i in range(n):yield iawait asyncio.sleep(1)async def process_data() -> None:async for num in async_range(5):print("Received:", num)asyncio.run(process_data())
    
  2. AwaitableGenerator: 表示可等待生成器类型。结合了 Generator 和 Awaitable,用于异步上下文中生成值并可使用 await 等待的类型。
    from typing import AwaitableGenerator
    import asyncioasync def async_generator() -> AwaitableGenerator[int, str, int]:yield 1await asyncio.sleep(1)yield 2await asyncio.sleep(1)yield 3async def process_generator() -> None:async for num in async_generator():print("Received:", num)asyncio.run(process_generator())
    
  3. AsyncContextManager: 表示异步上下文管理器类型。类似于 ContextManager,但用于异步上下文中支持 async with 语句的对象的类型
    from typing import AsyncContextManager
    import asyncioclass MyAsyncContextManager:async def __aenter__(self):print("Entering async context")async def __aexit__(self, exc_type, exc_value, traceback):print("Exiting async context")async def process_data(manager: AsyncContextManager) -> None:async with manager:print("Processing data")asyncio.run(process_data(MyAsyncContextManager()))
    
  4. MutableMapping: 可变的键值对映射类型,它是 Mapping 的子类
    from typing import MutableMappingdef process_data(data: MutableMapping[str, int]) -> None:data["count"] = 10my_dict: MutableMapping[str, int] = {"name":  "John", "age": 30}
    process_data(my_dict)
    print(my_dict)
    
  5. MutableSet: 可变的集合类型,它是 Set 的子类
    from typing import MutableSetdef process_data(data: MutableSet[int]) -> None:data.add(4)my_set: MutableSet[int] = {1, 2, 3}
    process_data(my_set)
    print(my_set)
    
  6. MappingView: 映射视图类型,它提供了对映射对象的只读访问
    from typing import MappingViewdef process_data(data: MappingView[str, int]) -> None:for key, value in data.items():print(key, value)my_dict = {"name": "John", "age": 30}
    process_data(my_dict.items())
  7. Match: 正则表达式匹配对象类型,用于表示匹配的结果
    from typing import Match
    import redef process_data(pattern: str, text: str) -> None:match: Match = re.search(pattern, text)if match:print("Match found:", match.group())else:print("No match found")process_data(r"\d+", "abc123def")
    
  8. MutableSequence: 可变的序列类型,它是 Sequence 的子类
    from typing import MutableSequencedef process_data(data: MutableSequence[int]) -> None:data.append(4)my_list: MutableSequence[int] = [1, 2, 3]
    process_data(my_list)
    print(my_list)
    

这篇关于python内置模块typing 类型提示的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/260055

相关文章

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e