Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: Handling exceptions while sorting
    primarykey
    data
    text
    <p>I have a list of objects that I need to sort according to a <a href="https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions" rel="nofollow" title="Key functions">key function</a>. The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception.</p> <p>Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result.</p> <p>My problem can be reconstructed using the following example: Suppose I have two classes, <code>Good</code> and <code>Bad</code>:</p> <pre><code>class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' </code></pre> <p>I want to sort instances of these classes according to their <code>x</code> property. Eg.:</p> <pre><code>&gt;&gt;&gt; sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] </code></pre> <p>Now, when there is a <code>Bad</code> in my list, the sorting fails:</p> <pre><code>&gt;&gt;&gt; sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError </code></pre> <p>I am looking for a magical function <code>func</code> that sorts a list according to a key function, but simply ignores elements for which the key function raised an error:</p> <pre><code>&gt;&gt;&gt; func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] </code></pre> <p>What is the most Pythonic way of achieving this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload