One liners
Roy Smith
roy at panix.com
Fri Dec 6 22:27:00 EST 2013
In article <52a287cb$0$30003$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> The ternary if is slightly unusual and unfamiliar
It's only unusual an unfamiliar if you're not used to using it :-)
Coming from a C/C++ background, I always found the lack of a ternary
expression rather limiting. There was much rejoicing in these parts
when it was added to the language relatively recently. I use them a lot.
On the other hand, I found list comprehensions to be mind-bogglingly
confusing when I first saw them (read: slightly unusual and unfamiliar).
It took me a long time to warm up to the concept. Now I love them.
> As for readability, I accept that ternary if is unusual compared to other
> languages, but it's still quite readable in small doses. If you start
> chaining them:
>
> result = a if condition else b if flag else c if predicate else d
>
> you probably shouldn't.
That I agree with (and it's just as true in C as it is in Python).
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 []
--------------------------------------------------
c2s = compids2songs(set(targets.keys()) |
set.union(*map(set,targets.itervalues())),self.docmap,self.logger) if
targets else {}
--------------------------------------------------
code = 2 if (pmp3,paac)==(mmp3,maac) else 3 if any(x is None for x in
(pmp3,paac,mmp3,maac)) else 4
--------------------------------------------------
Anybody else have some fun ternary abuse examples?
More information about the Python-list
mailing list