我在尝试注释一些代码时遇到了问题,但我无法真正理解它。我只是不知道这是否是 pylint 问题,或者我只是太愚蠢才弄清楚。
所以我得到了一个继承自 type 的类,并具有如下属性:
class MyType(type):
@property
def keys(cls) -> list[str]:
"""
Property to return a list of Keys
"""
result: list[str] = [key for key, val in vars(cls).items() if not callable(val)
and not key.startswith('__')
or not type(val).__name__ != 'method']
return result
所以我想我做了一个支持此属性的协议类,并且我可以在代码中使用此协议以及带注释的内容。
class IsMyType(Protocol):
"Protocol to implement an interface for key property"
@property
def keys(cls) -> list[str]: ...
所以现在当我尝试使用它时
foo: IsMyType = MyType(bar)
我收到 pylint 的抱怨
Expression of type "Type[__class_MyType]" cannot be assigned to declared type "IsMyType"
"keys" is an incompatible type
"property" is incompatible with "list[str]"PylancereportGeneralTypeIssues
我几乎只是在协议中返回 Any,这只是搞砸了或者只是尝试使用一些
#pylint: disabel=
关于这一点。最后的手段就是跳过整个打字过程。
因此,如果有人能解决类似情况,我们将不胜感激。
干杯
马库斯
不幸的是,这不是完整的答案。我将链接到下面的一些资源。
第一个问题是你的错误不是来自
pylint
,而是来自Pylance
,一个Python扩展(Python的VSCode扩展包的一部分),其中包括pyright类型检查器。在他们的 github 页面上搜索问题可能会有所帮助。
事实上,如果您从
(type)
类定义中删除 MyType
,您将看到您的代码片段通过了类型检查。我不知道这是否适用于您的代码库,但似乎属性在元类的上下文中以某种方式发生了变化?
一些链接