让PyCharm知道哪些类是mixin的 [英] Get PyCharm to know what classes are mixin for

查看:124
本文介绍了让PyCharm知道哪些类是mixin的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序具有一组复杂的表单向导.为了避免代码重复,我创建了多个mixin.

Our application has set of complex form wizards. To avoid code duplication I created several mixins.

问题在于PyCharm突出显示了Unresolved attribute refference错误的混合方法.
这是正确的,因为object没有这样的方法.但我知道此mixin将仅与特殊类一起使用.有什么办法可以将此信息告知PyCharm?

The problem is that PyCharm highlights mixin methods with Unresolved attribute refference error.
This is correct as object does not have such methods. But I know that this mixin will be used only with special classes. Is there any way to tell this info to PyCharm?

现在我使用这种方法:

class MyMixin(object):
    def get_context_data(self, **kwargs):
        assert isinstance(self, (ClassToBeExtended, MyMixin))
        # super.get_context_data is still highlighter, 
        # as super is considered as object
        context = super(MyMixin, self).get_context_data(**kwargs)
        context.update(self.get_preview_context())
        return context

    def get_preview_context(self):
        # without this line PyCharm highlights the self.initial_data
        assert isinstance(self, (ClassToBeExtended, MyMixin))
        return {'needs': (self.initial_data['needs']
                          if 'type' not in self.initial_data
                          else '%(needs)s %(type)s' % self.initial_data)}

虽然此方法在某些情况下(例如self.的自动完成)有效,但在其他情况下(例如super)则失败.有没有更好的方法来实现所需的行为?

While this works for some cases like autocomplete for self., it fails for other cases like super. Is there a better approach to achieve the desired behavior?

PS:我知道我可以禁用对特定名称或整个类的引用检查,但是我不想这样做,因为它在拼写检查和自动完成方面无济于事.

推荐答案

您可以输入提示到PyCharm期望什么样的类.

You can type-hint to PyCharm what kind of classes to expect.

class DictMixin(object):
    def megamethod(
        self,  # type: dict
        key
    ):
        return self.get(key)

它仍然不能与其他类型的处理程序相提并论. PyCharm懒于评估它,只有在第一次使用self时才这样做. 访问mixin的属性时,事情也有些棘手-self, # type: dict | DictMixin适用于我的一个类,但不适用于我的测试代码. 在 python 3.5 中,您应该可以使用 # type: typing.Union[dict, DictMixin] .

It's still not quite comparable to other type handling. PyCharm is lazy in evaluating it, and only does so when first working on self. Things are a bit tricky when accessing attributes of the mixin as well - self, # type: dict | DictMixin works for one of my classes, but not in my test code. In python 3.5, you should be able to use # type: typing.Union[dict, DictMixin].

这篇关于让PyCharm知道哪些类是mixin的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆