Python 3.11 中联合类型和类型变量的类型提示错误

问题描述 投票:0回答:1

我在 Visual Studio Code 中使用 Pylance 在 Python 3.11 中遇到了类型提示问题,我正在寻找有关发生此错误的原因以及如何解决它的见解。这是我的代码:

from typing import TypeAlias, TypeVar

Data: TypeAlias = int | str
DataVar = TypeVar("DataVar", int, str)

class A:
    def __init__(self):
        pass

    def do_something(self, X: Data) -> Data:
        return self._foo(X)  # <---- Pylance raises an error here!!

    def _foo(self, X: DataVar) -> DataVar:
        return X

但是,Pylance 提出了以下错误:

Argument of type "Data" cannot be assigned to parameter "X" of type "DataVar@_foo" in function "_foo"
  Type "Data" is incompatible with constrained type variable "DataVar"

我很难理解为什么会发生这个错误。据我所知,

Data
是一种灵活的类型,可以是
int
str
,并且
_foo
应该能够接受它作为参数。如果我以相反的顺序提供类型,即
do_something
期望得到
DataVar
并且
_foo
得到
Data
,我会期望出现错误(确实会引发)

  1. 为什么 Pylance 会提出这个错误?
  2. 是否有正确的方法来注释类型以避免此错误?
  3. 这是 Python 3.11 中类型检查器的限制或误报吗?

任何有关如何解决此问题的见解或建议将不胜感激。

type-hinting union-types pylance python-3.11 type-variables
1个回答
0
投票

Data
是什么类型?

from typing import reveal_type

Data: TypeAlias = int | str
reveal_type(Data) # Runtime type is 'UnionType'

它是联合类型。

另一方面,

TypeVar
文档说:

但是,使用约束类型变量(如您定义的)意味着 TypeVar 可以 只能作为给定的约束之一来解决。

所以

X
只能是
int
str
(或它们的子类)。
Union
类型不是其中任何一个的子类。这就是打字系统的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.