如何在 python 中键入提示元组变量?

How to type hint a tuple variable in python?

在 python 我有一个对象 data 可能是任何对象。
在vscodev1, v2 = data # type: str, str句中我要v1, v2 会弹出str方法
在vscodev1, v2 = data # type: dict, set句我要v1, v2 会弹出dict,设置方法

data = (object, object)

v1, v2 = data # type: str, str

v11, v22= data # type: dict, set

但是在pylance中显示错误

Type annotation not supported for this type of expression
Unexpected token at end of expression

不确定我是否正确理解了您的观点,但您可以声明数据类型,然后根据需要声明变量类型:

import typing as ty

data = ({}, 0.0)  # type: ty.Tuple[dict, float]

v1: "dict"
v2: "str"
v1, v2 = data

我无法在 vscode 上测试它,但上面给出了与 pyright(由 pylance 使用)一致的类型检查

编辑:整合@Abhijit 评论,python 3.9+ 将是:

data: tuple[dict, float] = ({}, 0.0)

v1: "dict"
v2: "str"
v1, v2 = data