python内置模块typing 类型提示

编程入门 行业动态 更新时间:2024-10-11 07:36:16

python内置<a href=https://www.elefans.com/category/jswz/34/1771428.html style=模块typing 类型提示"/>

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 类型提示

本文发布于:2023-12-05 17:21:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1664824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   提示   类型   python   typing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!