欢迎大家来到IT世界,在知识的湖畔探索吧!
一、简介
typing 是 Python 标准库中的一个模块,用于支持类型提示(Type Hints)。类型提示是一种在代码中指定变量、函数参数和返回值的类型的方法,它可以提供代码的可读性、可维护性和工具支持。
二、常用类型及示例
- Any:表示任意类型。
from typing import Any test:Any = 2 def process_data(data: Any) -> None: # 对任意类型的数据进行处理 pass
欢迎大家来到IT世界,在知识的湖畔探索吧!
- List:表示列表类型。
欢迎大家来到IT世界,在知识的湖畔探索吧!from typing import List test: List[int] = [2] def process_list(items: List[int]) -> None: # 处理整数列表 pass
- Tuple:表示元组类型。
from typing import Tuple test:Tuple[int] = (2,) def process_tuple(data: Tuple[str, int]) -> None: # 处理包含字符串和整数的元组 pass
- Dict:表示字典类型。
欢迎大家来到IT世界,在知识的湖畔探索吧!from typing import Dict test:Dict[str,int] = {"key":1} def process_dict(data: Dict[str, int]) -> None: # 处理键为字符串,值为整数的字典 pass
- Set:表示集合类型。
from typing import Set test: Set[int] = {2,3} def process_set(data: Set[str]) -> None: # 处理字符串集合 pass
- Union:表示多个可能的类型。
from typing import Union test:Union[int,str] = 2 def process_data(data: Union[int, float]) -> None: # 处理整数或浮点数 pass
- Optional:表示可选类型,即可以是指定类型或者 None。
from typing import Optional test:Optional[int] = None def process_data(data: Optional[str]) -> None: # 处理可选的字符串,可以为 None pass
- Callable:表示可调用对象的类型。
from typing import Callable def test(nu1: int, nu2: int) -> int: print('test') return nu1+nu2 def process_function(func: Callable[[int, int], int]) -> None: # 处理接受两个整数参数并返回整数的函数 print(func(2,2)) process_function(test)
- Iterator:表示迭代器类型。
from typing import Iterator test:Iterator[int] = iter([2]) def process_iterator(data: Iterator[int]) -> None: # 处理整数迭代器 pass
- Generator:表示生成器类型。
from typing import Generator def generate_numbers() -> Generator[int, None, None]: yield 1 yield 2 test: Generator[int, None, None] = generate_numbers()
- Iterable:表示可迭代对象的类型。
from typing import Iterable test:Iterable[str] = ["apple", "banana", "cherry"] tes1:Iterable[str] = ("apple", "banana", "cherry") def process_iterable(data: Iterable[str]) -> None: # 处理可迭代的字符串对象 pass
- Mapping:表示映射类型。
from typing import Mapping test:Mapping[str,int] = {"apple": 1, "banana": 2, "cherry": 3} def process_mapping(data: Mapping[str, int]) -> None: # 处理键为字符串,值为整数的映射对象 pass
- Sequence:表示序列类型。
from typing import Sequence test: Sequence[int] = [1, 2, 3, 4, 5] def process_sequence(data: Sequence[int]) -> None: # 处理整数序列 pass
- AnyStr:表示任意字符串类型。
from typing import AnyStr str:AnyStr = '213'
- NoReturn:表示函数没有返回值。
from typing import NoReturn def my_func() -> NoReturn: print("This function does not return anything") my_func()
- FrozenSet: 表示不可变的集合类型。类似于 Set,但不能进行修改。
from typing import FrozenSet def process_data(data: FrozenSet[str]) -> None: for item in data: print(item) test: FrozenSet[str] = frozenset(["apple", "banana", "orange"]) process_data(test)
- Literal: 表示字面值类型。用于指定变量的取值范围,只能是指定的字面值之一
from typing import Literal def process_color(color: Literal["red", "green", "blue"]) -> None: print("Selected color:", color) process_color("red") process_color("green") process_color("blue")
- AsyncGenerator: 表示异步生成器类型。类似于 Generator,但用于异步上下文中生成值的类型
from typing import AsyncGenerator import asyncio async def generate_data() -> AsyncGenerator[int, str]: yield 1 yield 2 yield 3 async def process_data() -> None: async for num in generate_data(): print("Received:", num) asyncio.run(process_data())
- ContextManager: 表示上下文管理器类型。用于定义支持 with 语句的对象的类型
from typing import ContextManager class 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())
- AsyncIterator: 表示异步迭代器类型。类似于 Iterator,但用于异步上下文中进行迭代的类型
from typing import AsyncIterator import asyncio async def async_range(n: int) -> AsyncIterator[int]: for i in range(n): yield i await asyncio.sleep(1) async def process_data() -> None: async for num in async_range(5): print("Received:", num) asyncio.run(process_data())
- Annotated: 用于添加类型注解的装饰器。可以在类型提示中添加额外的元数据信息
from typing import Annotated def process_data(data: Annotated[str, "user input"]) -> None: print("Received data:", data) process_data("Hello")
- AbstractSet: 表示抽象集合类型。是 Set 的基类,用于指定集合的抽象接口。通常用作父类或类型注解
from typing import AbstractSet def process_data(data: AbstractSet[str]) -> None: for item in data: print(item) my_set: AbstractSet[str] = {"apple", "banana", "orange"} process_data(my_set)
- Awaitable: 表示可等待对象的类型。用于指定可以使用 await 关键字等待的对象的类型。
from typing import Awaitable import asyncio async def async_task() -> int: await asyncio.sleep(1) return 42 async def process_task(task: Awaitable[int]) -> None: result = await task print("Task result:", result) asyncio.run(process_task(async_task()))
- AsyncIterable: 表示异步可迭代对象的类型。类似于 Iterable,但用于异步上下文中进行迭代的类型。
from typing import AsyncIterable import asyncio async def async_range(n: int) -> AsyncIterable[int]: for i in range(n): yield i await asyncio.sleep(1) async def process_data() -> None: async for num in async_range(5): print("Received:", num) asyncio.run(process_data())
- AwaitableGenerator: 表示可等待生成器类型。结合了 Generator 和 Awaitable,用于异步上下文中生成值并可使用 await 等待的类型。
from typing import AwaitableGenerator import asyncio async def async_generator() -> AwaitableGenerator[int, str, int]: yield 1 await asyncio.sleep(1) yield 2 await asyncio.sleep(1) yield 3 async def process_generator() -> None: async for num in async_generator(): print("Received:", num) asyncio.run(process_generator())
- AsyncContextManager: 表示异步上下文管理器类型。类似于 ContextManager,但用于异步上下文中支持 async with 语句的对象的类型
from typing import AsyncContextManager import asyncio class 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()))
- MutableMapping: 可变的键值对映射类型,它是 Mapping 的子类
from typing import MutableMapping def process_data(data: MutableMapping[str, int]) -> None: data["count"] = 10 my_dict: MutableMapping[str, int] = {"name": "John", "age": 30} process_data(my_dict) print(my_dict)
- MutableSet: 可变的集合类型,它是 Set 的子类
from typing import MutableSet def process_data(data: MutableSet[int]) -> None: data.add(4) my_set: MutableSet[int] = {1, 2, 3} process_data(my_set) print(my_set)
- MappingView: 映射视图类型,它提供了对映射对象的只读访问
from typing import MappingView def 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())
- Match: 正则表达式匹配对象类型,用于表示匹配的结果
from typing import Match import re def 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")
- MutableSequence: 可变的序列类型,它是 Sequence 的子类
from typing import MutableSequence def process_data(data: MutableSequence[int]) -> None: data.append(4) my_list: MutableSequence[int] = [1, 2, 3] process_data(my_list) print(my_list)
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/70292.html