检查类型提示是否被注释的正确方法是什么?

Python 3.9 引入了Annotated允许向类型提示添加任意元数据的类,例如,

class A:
    x: Annotated[int, "this is x"]

可以通过设置 的新include_extras参数来获得带注释的类型提示get_type_hints

>>> get_type_hints(A, include_extras=True)
{'x': typing.Annotated[int, 'this is x']}

并且元数据本身可以通过__metadata__类型提示的属性访问。

>>> h = get_type_hints(A, include_extras=True)
>>> h["x"].__metadata__
('this is x',)

但是,我的问题是,测试类型提示是否正确的正确方法 Annotated什么?也就是说,类似于:

if IS_ANNOTATED(h["x"]):
    # do something with the metadata

据我所知,没有记录在案的方法可以这样做,并且有几种可能的方法,但似乎都不理想。

比较typetoAnnotated不起作用,因为类型提示不是 的实例Annotated

>>> type(h["x"])
typing._AnnotatedAlias

所以我们必须这样做:

if type(h["x"]) is _AnnotatedAlias:
    ...

但是,鉴于 中的前导下划线_AnnotatedAlias,这可能需要使用实现细节。

另一种选择是直接检查__metadata__属性:

if hasattr(h["x"], "__metadata__"):
    ...

但这假设该__metadata__属性对于 是唯一的Annotated,在处理用户定义的类型提示时也不一定假设该属性。

那么,是否有更好的方法来进行此测试?

以上是检查类型提示是否被注释的正确方法是什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>