[英]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 Code 中从 Pylance 收到此错误:
在此上下文中不允许使用“ClassVar”
我正在使用 Python3.9 和 Pylance v2021.10.0。
在这个例子中, Email
类有一个“make_stub”函数,它的_not_overriden
属性设置为True
。 当我检查模块的该类的子类时,我可以使用它来过滤那些覆盖“make_sub”函数的模块。
我找不到有关此错误的任何文档。 有谁知道为什么会出现?
ClassVar
类型提示旨在标记类级变量,以告诉类型系统它们确实是类变量,而不是实例变量的默认值。
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
如果你的函数的参数应该是一个类,那么你应该使用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
。 由于PEP 585 ,您可以改用内置type
对象,该对象可以以相同的方式进行索引: cls: type["Emailer"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.