How to type hint a tuple variable in python?

Viewed 2183

In python I have a an object data that maybe any object it will be.
In vscode v1, v2 = data # type: str, str sentence I want v1, v2 will popup str method.
In vscode v1, v2 = data # type: dict, set sentence I want v1, v2 will popup dict, set method.

data = (object, object)

v1, v2 = data # type: str, str

v11, v22= data # type: dict, set

But it show error in pylance

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

Not sure I understood your point correctly, but you could declare data type and then variables types if needed:

import typing as ty

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

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

I cannot test it on vscode, but the above gives consistent type checking with pyright (which is used by pylance)

EDIT: integrating @Abhijit comment, for python 3.9+ would be:

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

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