python - 在旧版 Python 中创建带有可变参数的 Typing.Annotated 实例

标签 python type-hinting

问题只是如何重现这个:

import typing

a = [1, 2, 3]
cls = typing.Annotated[int, *a]

甚至是这个:

import typing

cls1 = typing.Annotated[int, 1, 2, 3]
unann_cls = typing.get_args(cls1)[0]
metadata = cls1.__metadata__
cls2 = typing.Annotated[unann_cls, *metadata]

在 Python 3.9-3.10 中。 Annotated[int, *a] 是 <3.11 中的语法错误,因此 typing_extensions.Annotated 在这里没有帮助。 “嵌套注释类型被扁平化”建议使用以下代码:

cls2 = unann_cls
for m in metadata:
    cls2 = typing.Annotated[cls2, m]

它似乎有效,但肯定应该有一个更干净的方法?

最佳答案

在表达式中

obj[1, 2, 3]

1, 2, 3 只是一个元组文字。完全一样

x = 1, 2, 3
obj[x]

我们只是将元组 (1, 2, 3) 传递给 __getitem__ .

要获得您想要的行为,您可以用括号将元组文字括起来,以便在元组文字内执行序列解包的语法:

>>> typing.Annotated[(int, *a)]
typing.Annotated[int, 1, 2, 3]

关于python - 在旧版 Python 中创建带有可变参数的 Typing.Annotated 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77275400/

相关文章:

python - CTRL+C 异常(exception)处理

python - 键入多种类型的提示值?

java - 如何使 Intellij IDEA 仅在悬停时显示推断局部变量的 Java 类型提示?

python - 在 Python Web 应用程序中允许单点登录需要什么?

python - 在我的 celery 应用程序中使用 django ORM 出现错误

python - 如何判断字符串a是否为字符串b的子串但不等于字符串b?

python - 类型提示 : when to annotate

python - Django - 通过相关字段的 ID 获取对象

php - 类变量中的类型提示

php - 带类型提示的类型提示 : Is the type attribute still required on @ORM\Column annotation when using PHP 7. 4 带类型提示?