Pylance:在这种情况下不允许 "ClassVar"?
Pylance: "ClassVar" is not allowed in this context?
具有以下功能:
from typing import ClassVar
def overrode_make_stub(cls: ClassVar["Emailer"]) -> bool:
return not (getattr(cls.make_stub, "_not_overridden", False))
我在 Visual Studio 代码中从 Pylance 收到此错误:
"ClassVar" is not allowed in this context
我正在使用 Python3.9 和 Pylance v2021.10.0.
在此示例中,Email
class 具有“make_stub”函数,该函数的 _not_overriden
属性设置为 True
。当我检查一个模块是否有 class 的子 class 时,我可以使用它来过滤那些覆盖“make_sub”函数的模块。
我找不到关于此错误的任何文档。有谁知道为什么会出现?
ClassVar
类型提示旨在标记 class 级变量,以告诉类型系统它们确实是 class 变量,而不是实例变量的默认值。
from typing import ClassVar
class Example:
x: int # x and y are being type hinted as instance variables
y: int
z: ClassVar[int] # z is being type hinted as a class variable instead
如果您的函数的参数应该是 class,那么 you should use typing.Type
作为类型提示。试试这个,暗示你期望 Emailer
:
的 subclass
from typing import Type
def overrode_make_stub(cls: Type["Emailer"]) -> bool:
return not (getattr(cls.make_stub, "_not_overridden", False))
请注意,如果您只需要与 Python 3.9 及更高版本兼容,则实际上根本不需要使用 typing.Type
。你可以使用内置的 type
对象,它可以用同样的方式索引,感谢 PEP 585: cls: type["Emailer"]
具有以下功能:
from typing import ClassVar
def overrode_make_stub(cls: ClassVar["Emailer"]) -> bool:
return not (getattr(cls.make_stub, "_not_overridden", False))
我在 Visual Studio 代码中从 Pylance 收到此错误:
"ClassVar" is not allowed in this context
我正在使用 Python3.9 和 Pylance v2021.10.0.
在此示例中,Email
class 具有“make_stub”函数,该函数的 _not_overriden
属性设置为 True
。当我检查一个模块是否有 class 的子 class 时,我可以使用它来过滤那些覆盖“make_sub”函数的模块。
我找不到关于此错误的任何文档。有谁知道为什么会出现?
ClassVar
类型提示旨在标记 class 级变量,以告诉类型系统它们确实是 class 变量,而不是实例变量的默认值。
from typing import ClassVar
class Example:
x: int # x and y are being type hinted as instance variables
y: int
z: ClassVar[int] # z is being type hinted as a class variable instead
如果您的函数的参数应该是 class,那么 you should use typing.Type
作为类型提示。试试这个,暗示你期望 Emailer
:
from typing import Type
def overrode_make_stub(cls: Type["Emailer"]) -> bool:
return not (getattr(cls.make_stub, "_not_overridden", False))
请注意,如果您只需要与 Python 3.9 及更高版本兼容,则实际上根本不需要使用 typing.Type
。你可以使用内置的 type
对象,它可以用同样的方式索引,感谢 PEP 585: cls: type["Emailer"]