Python 3.0, rich comparisons and sorting order
Steven Bethard
steven.bethard at gmail.com
Wed Sep 22 04:36:11 EDT 2004
Alex Martelli <aleaxit <at> yahoo.com> writes:
>
> I wrote:
> ...
> > (2) "is there a good use case for wanting to make a mapping with keys that
> > have incompatible types?" (my question to you)
> >
> > To some degree, (1) has already been answered to my satisfaction by Carlos
> > Ribeiro's spreadsheet example. If you could give me a real world example
> > of when you'd want to do (2), I might be more convinced...
>
> Does my example of 'tuples as concrete representations of expressions'
> which I posted to another subthread of this thread help?
Yeah, thanks. It's still definitely not the kind of computation that 99% of
users are going to want to do, but if you wanted to memoize such tuples and
you also expected hashing said tuples to be more expensive than cmp'ing them,
I can see that the mapping you replace dict with would need to be able to sort
disparate types.
'Course rather than wrap your expression tuples in a class to define the
__cmp__ function, it seems like a more reasonable solution might be to make
the arbitrary cmp decision in the mapping class (the one implemented as a
BTree). If __cmp__ starts raising TypeErrors, your code could do something
like:
def insert(self, val):
try:
c = cmp(self.val, val)
except TypeError:
c = -1 # self.val and val were not of the same type
# make some arbitrary decision here
... # insert according to cmp result
Does take more work than it would now -- forces the arbitrary decision onto
the BTree writer, instead of doing it automatically in cmp... How much more
work really depends on how complicated your 'arbitrary' scheme is...
Steve
More information about the Python-list
mailing list