Mixin 方法 super() 调用在 PyCharm 中生成未解析的属性引用

Tec*_*oft 6 python typing pycharm

在 PyCharm 中,我有一些看起来像这样的代码:

class Mixin:
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update({'foo': 'bar'})
        return kwargs
Run Code Online (Sandbox Code Playgroud)

短绒Unresolved attribute reference 'get_form_kwargs' for class 'object'super()电话中提出了一个问题。这个问题 100% 正确,但对 mixin 没有帮助。我们有很多具有这种super()模式的mixin 。

我知道属性的解决方案,但不知道您可以为这些未定义的类属性声明类型的方法。例如:

class Mixin:
    foo:str
Run Code Online (Sandbox Code Playgroud)

我很好奇是否有任何类似的方法可以帮助 linter 识别 mixin。

谢谢!

Vla*_*kov -3

Try this code:

class Mixin:
    def get_form_kwargs(self):
        get_form_kwargs_method = getattr(super(), "get_form_kwargs")
        if get_form_kwargs_method and callable(get_form_kwargs_method):
            kwargs = get_form_kwargs_method()
        else:
            kwargs = {}
        kwargs.update({'foo': 'bar'})
        return kwargs
Run Code Online (Sandbox Code Playgroud)

Update: I'd appreciate a comment from those who added - on this answer. This definitely fixes a pylint issute. This is not short and elegant, but you have 2 choices: disable this check in pylint or write a valid code.

在此输入图像描述