[Tutor] this group and one liners

Mats Wichmann mats at wichmann.us
Thu Jul 7 11:38:20 EDT 2022


On 7/6/22 11:02, avi.e.gross at gmail.com wrote:

Boy, we "old-timers" do get into these lengthy discussions...  having
read several comments here, of which this is only one:

> The excuse for many one-liners is often that they are in some ways better as in use less memory or are faster in some sense.
> 
> Although that can be true, I think it is reasonable to say that often the exact opposite is true.
> 
> In order to make a compact piece of code, you often twist the problem around in a way that makes it possible to leave out some cases or not need to handle errors and so on. I did this a few days ago until I was reminded max(..., default=0) handled my need. Some of my attempts around it generated lots of empty strings which were all then evaluated as zero length and then max() processed a longer list with lots of zeroes.


After a period when they felt awkward because lots of my programming
background was in languages that didn't have these, I now use simple
one-liners extensively - comprehensions and ternary expressions.  If
they start nesting, probably not.  Someone mentioned a decent metric -
if a code formatter like Black starts breaking your comprehension into
four lines, it probably got too complex.

My take on these is you can write a more compact function this way -
you're more likely to have the meat of what's going on right there
together in a few lines, rather than building mountain ranges of
indentation - and this can actually *improve* readability, not obscure
it.  I agree "clever" one-liners may be a support burden, but anyone
with a reasonable amount of Python competency (which I'd expect of
anyone in a position to maintain my code at a later date) should have no
trouble recognizing the intent of simple ones.

Sometimes thinking about how to write a concise one-liner exposes a
failure to have thought through what you're doing completely - so unlike
what is mentioned above - twisting a problem around unnaturally (no
argument that happens too), you might actually realize that there's a
simpler way to structure a step.

Just one more opinion.


More information about the Tutor mailing list