我们的应用程序有一组复杂的表单向导。为了避免代码重复,我创建了几个 mixins。
问题是 PyCharm 突出显示了带有 Unresolved attribute reference
错误的 mixin 方法。
这是正确的,因为 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
等其他情况无效。是否有更好的方法来实现所需的行为?
P.S.:我知道我可以禁用特定名称或整个类(class)的引用检查,但我不想这样做,因为它对拼写错误检查和自动完成没有帮助。
最佳答案
您可以 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]
.
关于python - 让 PyCharm 知道哪些类是 mixin 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33956505/