Python中含@context键的字典类型定义方法
解决TypedDict中含@符号的键定义问题
因为@context中的@是Python装饰器的语法前缀,无法直接作为类属性名使用,你可以通过以下两种方式定义该结构的TypedDict类型:
方法一:使用字符串字面量作为键(Python 3.8+)
在TypedDict类中,将带特殊符号的键用引号包裹,作为注解的一部分:
from typing import TypedDict class Result(TypedDict): "@context": str id: str type: str protocol: str profile: str width: int height: int maxHeight: int maxWidth: int maxArea: int
方法二:使用TypedDict构造函数定义(全版本兼容)
直接通过TypedDict构造函数传入键值对字典,避开类属性命名限制:
from typing import TypedDict Result = TypedDict( 'Result', { '@context': str, 'id': str, 'type': str, 'protocol': str, 'profile': str, 'width': int, 'height': int, 'maxHeight': int, 'maxWidth': int, 'maxArea': int } )
使用示例
两种定义方式都能正常通过类型检查:
my_result: Result = { "@context": "example_string", "id": "example_string", "type": "example_string", "protocol": "example_string", "profile": "example_string", "width": 0, "height": 0, "maxHeight": 0, "maxWidth": 0, "maxArea": 0 }
内容的提问来源于stack exchange,提问作者Damianzs
相关产品推荐
相关产品推荐

