让PyCharm知道mixin的类是什么

时间:2015-11-27 11:35:02

标签: python django ide pycharm mixins

我们的应用程序有一组复杂的表单向导。为了避免代码重复,我创建了几个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)}

虽然这适用于某些情况,例如self.的自动填充功能,但对于super等其他情况则无效。有没有更好的方法来实现理想的行为?

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

2 个答案:

答案 0 :(得分:6)

你可以type-hint向PyCharm提出什么样的课程。

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]

答案 1 :(得分:2)

如果你正在创建Mixin,那么,让我们说ClassSub,它是ClassSuper的子类,你可以用这种方式实现Mixins:

class Mixin1(ClassSuper):
    pass


class Mixin2(ClassSuper):
    pass

然后使用它们:

class ClassSub(Mixin1, Mixin2):
    pass

这样我在Django中使用了一些mixins模型。此外,django-extensions使用类似的模式(给出实际上是mixins的模型)。基本上,这种方式你不必继承ClassSuper,因为它包括&#34;&#34;包括&#34;在你的每个混音中。

最重要的是 - PyCharm就像这样的魅力。