在pylint和mypy中处理Python类重新定义警告

2024-07-03 07:10:32 发布

您现在位置:Python中文网/ 问答频道 /正文

SQLAlchemy backrefs在变得复杂时往往会导致循环导入,因此我想出了一种方法来“重新打开”一个类似Ruby的Python类:

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现有的relationship+backref机制不足以插入双向SQLAlchemy关系和助手方法,那么这段代码可以很好地工作

然而:

  1. mypy引发错误“名称'ExistingClass'已定义(可能由导入定义)”
  2. pylint引发E0102“类已定义”

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

我该怎么做


Tags: the方法selfnew定义sqlalchemydefproperty