5

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
jett chen
  • 1,067
  • 16
  • 33

1 Answers1

3

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
luco00
  • 501
  • 5
  • 9
  • if my `data = [int, str, set, dict, byte, objectA, objectB, .... objectN]`, this method is not good, it only useful for short container variable. – jett chen Jul 14 '21 at 00:50
  • Isn't a limit of type hinting itself? If you have n variable that you want to hint you would always end up hinting n variable. Or am I missing something? Also, declaring v1 and/or v2 is optional; you could do it only for the variables you want to be checked. In any case, the above provides syntax to declare tuples as you asked; see also other comments and check docs [here](https://docs.python.org/3/library/typing.html) for example. The n variables hinting problem is a different question and its not fair to extra complexity after the question was answered... – luco00 Jul 14 '21 at 08:18
  • yes, It's problem of Pylance. your answer is right in my question. – jett chen Jul 14 '21 at 08:28