微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

处理Pylint和Mypy中的Python类重新定义警告

如何解决处理Pylint和Mypy中的Python类重新定义警告

sqlAlchemy反向引用往往会导致复杂的循环导入,因此我想出了一种“重新打开” Python类的方法,就像在Ruby中一样:

def reopen(cls):
    """
    Moves the contents of the decorated class into an existing class and returns that.

    Usage::

        from .other_module import ExistingClass

        @reopen(ExistingClass)
        class ExistingClass:
            @property
            def new_property(self):
                pass

    This is equivalent to::

        def new_property(self):
            pass

        ExistingClass.new_property = property(new_property)
    """

    def decorator(temp_cls):
        for attr,value in temp_cls.__dict__.items():
            # Skip the standard Python attributes,process the rest
            if attr not in ('__dict__','__doc__','__module__','__weakref__'):
                setattr(cls,attr,value)
        return cls

    return decorator

这是简化版本; the full implementation has more safety checks和测试。

代码可在sqlAlchemy现有的关系+ backref机制不足的地方插入双向sqlAlchemy关系和辅助方法

但是:

  1. mypy引发错误“已经定义了名称“ ExistingClass”(可能是通过导入)”
  2. pylint引发E0102“类已定义”

我可以通过在行上添加注解(# type: ignore# skipcq来忽略这两个错误,但是过度使用这些注解会导致bug溜走。告诉mypy和pylint这样的用法是可以的。

我该怎么做?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。