如何在Python 3中为映射类到对应实例的字典添加类型提示
Python 3 类到实例映射字典的类型提示方案
基础通用标注
如果你的字典支持存储任意类和对应实例,直接使用Type[Any]作为键的类型、Any作为值的类型即可:
# Python 3.9+ 原生dict写法 from typing import Type, Any d: dict[Type[Any], Any] = {} d[int] = 0 d[str] = "hello world" # Python 3.8及更早版本写法 from typing import Dict, Type, Any d: Dict[Type[Any], Any] = {}
限定类型范围的标注
如果字典只允许存储指定几类的映射,可以用TypeVar做泛型约束,避免非法类型写入:
from typing import TypeVar, Type, Dict # 限定仅支持int、str、bool三类 AllowedType = TypeVar("AllowedType", int, str, bool) d: Dict[Type[AllowedType], AllowedType] = {} d[int] = 123 # 类型校验通过 d[str] = "test" # 类型校验通过 d[float] = 1.5 # 类型检查工具会抛出错误,float不在允许范围内
类型安全的自定义容器实现
如果需要取值时也能自动识别对应类型,可以自定义泛型容器类实现强类型校验:
from typing import TypeVar, Generic, Type, Optional T = TypeVar('T') class TypeMap(Generic[T]): def __init__(self): self._store: dict[Type[T], T] = {} def put(self, typ: Type[T], value: T) -> None: self._store[typ] = value def get(self, typ: Type[T]) -> Optional[T]: return self._store.get(typ) # 调用示例 my_map = TypeMap() my_map.put(int, 200) my_map.put(str, "你好") int_val = my_map.get(int) # 类型工具自动识别int_val为Optional[int] str_val = my_map.get(str) # 自动识别为Optional[str]
内容的提问来源于stack exchange,提问作者nullUser
相关产品推荐
相关产品推荐

