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关系和助手方法,那么这段代码可以很好地工作
然而:
我可以通过在行(# type: ignore
和# skipcq
)上添加注释来忽略这两个错误,但是过度使用这些注释会让bug溜走。告诉mypy和pylint这种用法是可以的
我该怎么做
目前没有回答
相关问题 更多 >
编程相关推荐