'Is there correct way to use python typing?
I'm trying to figure out typing in Python and I'm having trouble with the following code:
from collections.abc import Iterable
from typing import TypeVar
T = TypeVar('T')
def convert_to_iter(var: T | Iterable[T]) -> Iterable[T]:
if not isinstance(var, Iterable):
return (var, )
return var
I am using Pylance in VScode with typeCheckingMode: "strict" and am getting the error on the last line of the code:
Return type, "Iterable[Unknown]* | Iterable[T@convert_to_list]", is partially unknown Pylance(reportUnknownVariableType)
Can someone please explain why this is incorrect?
Solution 1:[1]
There is a discussion in this issue about such question.
So, this behavior can be explained by type narrowing.
One of the existing ways to eliminate this error is to use cast function
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EvgeniyMist |
