typing 是 Python 标准库中的一个模块,用于支持类型提示(Type Hints)。类型提示是一种在代码中指定变量、函数参数和返回值的类型的方法,它可以提供代码的可读性、可维护性和工具支持。
from typing import Any
test:Any = 2
def process_data(data: Any) -> None:
# 对任意类型的数据进行处理
pass
from typing import List
test: List[int] = [2]
def process_list(items: List[int]) -> None:
# 处理整数列表
pass
from typing import Tuple
test:Tuple[int] = (2,)
def process_tuple(data: Tuple[str, int]) -> None:
# 处理包含字符串和整数的元组
pass
from typing import Dict
test:Dict[str,int] = {"key":1}
def process_dict(data: Dict[str, int]) -> None:
# 处理键为字符串,值为整数的字典
pass
from typing import Set
test: Set[int] = {2,3}
def process_set(data: Set[str]) -> None:
# 处理字符串集合
pass
from typing import Union
test:Union[int,str] = 2
def process_data(data: Union[int, float]) -> None:
# 处理整数或浮点数
pass
from typing import Optional
test:Optional[int] = None
def process_data(data: Optional[str]) -> None:
# 处理可选的字符串,可以为 None
pass
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)
from typing import Iterator
test:Iterator[int] = iter([2])
def process_iterator(data: Iterator[int]) -> None:
# 处理整数迭代器
pass
from typing import Generator
def generate_numbers() -> Generator[int, None, None]:
yield 1
yield 2
test: Generator[int, None, None] = generate_numbers()
from typing import Iterable
test:Iterable[str] = ["apple", "banana", "cherry"]
tes1:Iterable[str] = ("apple", "banana", "cherry")
def process_iterable(data: Iterable[str]) -> None:
# 处理可迭代的字符串对象
pass
from typing import Mapping
test:Mapping[str,int] = {"apple": 1, "banana": 2, "cherry": 3}
def process_mapping(data: Mapping[str, int]) -> None:
# 处理键为字符串,值为整数的映射对象
pass
from typing import Sequence
test: Sequence[int] = [1, 2, 3, 4, 5]
def process_sequence(data: Sequence[int]) -> None:
# 处理整数序列
pass
from typing import AnyStr
str:AnyStr = '213'
from typing import NoReturn
def my_func() -> NoReturn:
print("This function does not return anything")
my_func()
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)
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")
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())
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())
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())
from typing import Annotated
def process_data(data: Annotated[str, "user input"]) -> None:
print("Received data:", data)
process_data("Hello")
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)
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()))
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())
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())
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()))
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)
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)
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())
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")
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)