Ticket #37 (new discussion)

Opened 2 years ago

Last modified 21 months ago

Provide a __cmp__ method for Entity.

Reported by: pobrien Owned by:
Priority: normal Milestone: Schevo 3.1
Component: Schevo Keywords:
Cc:

Description (last modified by pobrien) (diff)

The idea here is to provide smart sorting of entities out-of-the-box for use by applications like GUI navigators. This __cmp__ method should compare the (primary-key-values, entity-name) of the Entity instance. Where the primary key includes an entity field it may need to recurse into that entity for additional values (unless Python does that by default already). Including the entity-name is important for sorting heterogenous collections.

Change History

Changed 2 years ago by pobrien

  • description modified (diff)

Changed 2 years ago by pobrien

Another approach occured to me. Here is a typical __cmp__ method:

    def __cmp__(self, other):
        if other is UNASSIGNED:
            return 1
        try:
            return cmp((self.foo, self.bar), (other.foo, other.bar))
        except AttributeError:
            return cmp(hash(self), hash(other))

The _key() of this Entity might not be _key(foo, bar), or may not be in that order. So perhaps another helper function could be introduced, like this:

class Example(E.Entity):

    alpha = f.string()
    foo = f.string()
    bar = f.string()

    _key(alpha)

    _cmp(foo, bar)

The Entity metaclass would then use this information to construct a __cmp__ method that looked something like this:

    def __cmp__(self, other):
        if other is UNASSIGNED:
            return 1
        try:
            this = (getattr(self, 'foo'), getattr(self, 'bar')
            that = (getattr(other, 'foo'), getattr(other, 'bar')
            return cmp(this, that)
        except AttributeError:
            return cmp(hash(self), hash(other))

Or we could have a generic __cmp__ that relied on some helper function:

    def __cmp__(self, other):
        return schevo.compare(self, other, self._cmp_fields)

The _cmp_fields attribute would be a list of strings populated by the _cmp() helper.

The last approach has the most flexibility for improving comparisons without having to rebuild existing database files.

Changed 2 years ago by pobrien

One issue I forgot to mention. The _cmp() function (and all other supporting code) needs to allow one to drill down into entity fields, like this:

    _cmp(foo, bar, baz.type.number)

Changed 21 months ago by mscott

  • milestone set to Schevo 3.1

pobrien, I see there is a cmp implementation in source:/tags/releases/Schevo-3.0/schevo/entity.py#L340

Are you thinking that the default cmp implementation as it stands should be the default, and the _cmp() declarations you describe above would override it?

If so, let's keep this in the Schevo 3.1 milestone; if not, let's mark it as wontfix.

Note: See TracTickets for help on using tickets.