One liners

Jussi Piitulainen jpiitula at ling.helsinki.fi
Sat Dec 7 07:41:17 EST 2013


Steven D'Aprano writes:

> On Fri, 06 Dec 2013 22:27:00 -0500, Roy Smith wrote:
> 
> > Just for fun, I took a look through the Songza code base.  66 kloc of
> > non-whitespace Python.  I found 192 ternary expressions.  Here's a few
> > of the more bizarre ones (none of which I consider remotely readable):
> > 
> > -------------------------------------------------- 
> > extracols = ( sorted(set.union(*(set(t.data.keys()) for t in tracks)))
> >               if tracks else [] )
> 
> [extra parentheses added so I can split the line over two]
> 
> I actually don't find that too bad, readability-wise. Not ideal, but I 
> can follow it. However, I wonder why t.data.keys() is converted to a set 
> before being unpacked? Even assuming that data.keys are not necessarily 
> unique, wouldn't building the union make them so?
> 
> extracols = ( sorted(set.union(*(t.data.keys()) for t in tracks)))
>               if tracks else [] )
> 
> 
> Also, you can get rid of the `if tracks` check altogether by using a 
> bound method instead of an unbound method:
> 
> extracols = sorted(set().union(*(t.data.keys()) for t in tracks))
> 
> ought to work even if tracks is empty.

I suspect in the original code tracks could be None (or False) and
then the part of the code that bombs is 'for t in tracks' because
tracks is not iterable.

One could write [f(t) for t in tracks or []] and it wouldn't be blamed
on a binary operator - or maybe it would - but I suspect the cleaner
design would be to first make sure that an empty tracks is an empty
list (or an empty whatever-it-needs-to-be):

  if tracks is None:
     tracks = []
  ...
  extracols = sorted(set.union(*(t.data.keys()) for t in tracks))

Still, is t.data.keys() a collection of sets? Maybe frozensets? And
then their unions are being sorted by set inclusion, which is not a
total order. Does sorted work correctly with a partial order? I don't
think it does.



More information about the Python-list mailing list