让PyCharm知道mixin的类是什么

Igo*_*gor 10 python ide django mixins pycharm

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

问题是PyCharm突出了mixin方法的Unresolved attribute refference错误.
这是正确的,因为object没有这样的方法.但我知道这个mixin只能用于特殊课程.有没有办法告诉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)}
Run Code Online (Sandbox Code Playgroud)

虽然这适用于某些情况,例如自动完成功能self.,但是对于其他情况,它会失败super.有没有更好的方法来实现理想的行为?

PS:我知道我可以禁用特定名称或全班的参考检查,但我不想这样做,因为它无法帮助进行拼写检查和自动完成.

Mis*_*agi 6

您可以向PyCharm 键入提示以期望什么样的类。

class DictMixin(object):
    def megamethod(
        self,  # type: dict
        key
    ):
        return self.get(key)
Run Code Online (Sandbox Code Playgroud)

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