Single line if statement with a continue

avi.e.gross at gmail.com avi.e.gross at gmail.com
Thu Dec 15 01:58:11 EST 2022


Unless someone is counting lines of code for some purpose, like number of
error found per thousand lines of code, many short one-liners strike me as
more readable and especially if followed by a blank line so it is a bit
obvious.

Consider a similar issue in many languages that use curly braces and where
they can be skipped in a one liner like "if (condition) statement" rather
than the style some use on multiple lines like:

If (condition) {
  Statement
}

Or even:

If (condition)
  {
  Statement
  }


Of course, once you have additional parts following like an "else" that
contains multiple statements, it seems more symmetric to do both parts the
same style.

And in commented code, a one-liner may get long and harder to read as in 

If (condition) statement # long comment

Note the above are not python and the absence of a colon is intentional. No
one language is being discussed and some have their own vagaries and
variants such as not knowing if your code is done if you change lines in
ambiguous situations.  And note some languages support methods like the ?:
operator or the inline if/else python allows as in this:

min = 5
low = 12
x = low if low >= 12 else min
x
12
low = 3
x = low if low >= 12 else min
result
12

Clearly that is a one-liner that almost has to be a one liner as there is no
obvious easy way to wrap it into multiple lines.

I mean the following works, albeit darned if I know if any of it should be
indented or who wants to read it this way:

x = low \
    if \
      low >= 12 \
    else \
      min
    
x
5

As many have discussed, it is a matter of taste and people should be
flexible enough to program in whatever style others want to see when that
applies such as working in a group project or fixing someone else's code.


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On
Behalf Of dn
Sent: Thursday, December 15, 2022 12:24 AM
To: python-list at python.org
Subject: Re: Single line if statement with a continue

On 15/12/2022 07.53, Aaron P wrote:
> I occasionally run across something like:
> 
> for idx, thing in enumerate(things):
>      if idx == 103:
>          continue
>      do_something_with(thing)
> 
> It seems more succinct and cleaner to use:
> 
> if idx == 103: continue.
> 
> Of course this would be considered an anti-pattern, and Flake8 will
complain.
> 
> Any opinions, or feedback on the matter.


These aged-eyes prefer the second line and indentation.


However, another alternative (given simplicity of example):

for ...
     if idx != 103:
         do_something ...


Which could, in-turn, be boiled-down to a 'one-liner'.

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list