定义含dict[str, T]的JSON类型TypeVar时类型检查报错求助
解决TypeVar约束不能为泛型的问题
错误原因
你尝试给TypeVar指定的约束里包含了dict[str, T]、list[T]这类泛型类型,但TypeVar的约束仅支持非泛型的具体类型,因此类型检查器报错。
正确解决方案
要定义递归的JSON合法类型,应该使用类型别名(TypeAlias)结合递归Union类型,而非TypeVar直接约束泛型。以下是不同Python版本的实现方式:
Python 3.10+(支持|运算符)
from typing import TypeAlias JSONType: TypeAlias = str | float | int | bool | None | list["JSONType"] | dict[str, "JSONType"]
Python 3.9及以下
from typing import TypeAlias, Union, List, Dict JSONType: TypeAlias = Union[ str, float, int, bool, None, List["JSONType"], Dict[str, "JSONType"] ]
Python 3.11+(支持无引号自引用)
from typing import TypeAlias JSONType: TypeAlias = str | float | int | bool | None | list[JSONType] | dict[str, JSONType]
结合TypeVar使用(可选)
如果需要在函数中标注与输入同类型的JSON结构,可以用TypeVar绑定上述JSONType:
from typing import TypeVar, TypeAlias JSONType: TypeAlias = str | float | int | bool | None | list[JSONType] | dict[str, JSONType] T = TypeVar('T', bound=JSONType) def process_json(data: T) -> T: # 示例处理逻辑 if isinstance(data, list): return [process_json(item) for item in data] # type: ignore elif isinstance(data, dict): return {k: process_json(v) for k, v in data.items()} # type: ignore return data
内容的提问来源于stack exchange,提问作者NoneName
相关产品推荐
相关产品推荐

