Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52355 > unrolled thread

Re: Elegant compare

Started byChris Angelico <rosuav@gmail.com>
First post2013-08-11 04:45 +0100
Last post2013-08-11 04:45 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Elegant compare Chris Angelico <rosuav@gmail.com> - 2013-08-11 04:45 +0100

#52355 — Re: Elegant compare

FromChris Angelico <rosuav@gmail.com>
Date2013-08-11 04:45 +0100
SubjectRe: Elegant compare
Message-ID<mailman.462.1376192748.1251.python-list@python.org>
On Sun, Aug 11, 2013 at 4:41 AM, Jason Friedman <jsf80238@gmail.com> wrote:
> class my_class:
>     def __init__(self, attr1, attr2):
>         self.attr1 = attr1 #string
>         self.attr2 = attr2 #string
>     def __lt__(self, other):
>         if self.attr1 < other.attr1:
>             return True
>         else:
>             return self.attr2 < other.attr2
>
> I will run into problems if attr1 or attr2 is None, and they
> legitimately can be.
>
> I know I can check for attr1 or attr2 or both being None and react
> accordingly, but my real class has ten attributes and that approach
> will be long.  What are my alternatives?

The first question is: What should the comparison do with a None
value? Should it be considered less than every string? If so, you
could simply use:

if (self.attr1 or "") < (other.attr1 or ""):

which will treat any falsy value as blank.

ChrisA

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web