【问题标题】:Overriding __cmp__, __eq__, and __hash__ for SQLAlchemy Declarative Base为 SQLAlchemy 声明式基础覆盖 __cmp__、__eq__ 和 __hash__
【发布时间】:2011-03-28 01:27:06
【问题描述】:

我想覆盖 __cmp____eq____hash__,以便我可以在 SQLAlchemy 声明式基础模型上执行设置操作。这会导致与声明式基本实现发生冲突吗?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    没有。它会工作得很好。

    【讨论】:

    • 你能引用任何 SQLAlchemy 文档表明这样可以吗?
    • @DuneBug 我不明白为什么会有问题。 Sqlalchemy 本身不会覆盖声明性基础的那些特殊方法。
    • 如果 SQLAlchemy 曾经像@ovidi 提到的那样使用 eq,这可能是个问题。
    【解决方案2】:

    也许,取决于比较函数的实现。

    使用__eq____cmp__other 对象进行比较时必须小心,因为SQLAlchemy 可能会将您的对象与一些不具有相同类型的符号(例如NEVER_SET)进行比较。看看这个 SQLAlchemy 方法:

    def get_all_pending(self, state, dict_):
        if self.key in dict_:
            current = dict_[self.key]
            if current is not None:
                ret = [(instance_state(current), current)]
            else:
                ret = [(None, None)]
    
            if self.key in state.committed_state:
                original = state.committed_state[self.key]
                if original not in (NEVER_SET, PASSIVE_NO_RESULT, None) and \
                    original is not current:
    
                    ret.append((instance_state(original), original))
            return ret
        else:
            return []
    

    如果比较不首先检查类型的相等性或比较中使用的字段是否存在,original not in (NEVER_SET, PASSIVE_NO_RESULT, None) 行可能会引发错误

    作为一种解决方案,您应该考虑不同的类型。

    同时避免覆盖__cmp__ 并使用rich comparison operators instead

    【讨论】:

    • 好收获!这很重要。
    猜你喜欢
    • 2020-08-28
    • 2011-03-05
    • 1970-01-01
    • 2014-05-06
    • 2010-10-22
    • 1970-01-01
    • 2015-02-11
    • 2022-01-05
    • 2015-07-09
    相关资源
    最近更新 更多