Python Annotated
本文最后更新于 2026年7月18日
在Python中,Annotated主要指typing.Annotated,是Python 3.9引入的一个类型提示工具。它的核心作用是:给类型添加额外的元数据(metadata),而本身不改变类型的行为,类似Java 的注解。
Annotated的写法是:Annotated[类型,元数据,元数据..],其中:类型是必须遵守的约束,元数据可以是任何内容:字符串,数字,函数,lambda
from typing import Annotated
Age = Annotated[int, '年龄,必须大于等于0']
msgList = Annotated[list, lambda x,y: x+y]在类中使用Annotated标注的类型
from typing import Annotated, TypedDict
Age = Annotated[int, '年龄,必须大于等于0']
class Cat(TypedDict):
age: Age
或:
from typing import Annotated, TypedDict
class Cat(TypedDict):
age: Annotated[int, '年龄,必须大于等于0']但是Annotated仅仅只能做标注,不能进行校验,两段代码都能正常运行:
if __name__ == '__main__':
cat = Cat(age=-12)
print(cat['age']) # -12获取类型上面的元信息,通过get_type_hints()
from typing import Annotated, TypedDict
from typing import get_type_hints
Age = Annotated[int, '年龄,必须大于等于0']
msgList = Annotated[list, lambda x,y: x+y]
class Cat(TypedDict):
age: Age
if __name__ == '__main__':
type_hints = get_type_hints(Cat, include_extras=True)
print(type_hints['age'].__metadata__)('年龄,必须大于等于0',)"如果文章对您有帮助,可以请作者喝杯咖啡吗?"
微信支付
支付宝
Python Annotated
https://blog.liuzijian.com/post/python/2026/04/12/python-annotated/