简体   繁体   中英

How to type hint a tuple variable in python?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM