• Single line if statement with a continue

    From Aaron P@21:1/5 to All on Wed Dec 14 10:53:10 2022
    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.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Aaron P on Wed Dec 14 19:30:08 2022
    Aaron P <[email protected]> writes:
    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.

    I think tools like Flake8 check whether the style adheres to
    a certain set of style rules /for those users/ who like that
    particular ruleset. I can see no harm in writing "if idx ==
    103: continue" all on a single line. I think, if one adds

    [flake8]
    ignore = E701

    to the configuration file of Flake8, it is possible that
    this complaint will go away while other rules are still
    being checked. But I have not tested this. Maybe it's not
    the right number!

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Chris Angelico@21:1/5 to Aaron P on Thu Dec 15 15:35:28 2022
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]> 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.

    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Thomas Passin@21:1/5 to Chris Angelico on Thu Dec 15 00:06:43 2022
    PEP-8, which is Guido's style guide and generally good to follow, does
    not completely discourage single-line usage like the example. It's not
    clear to me how Chris's example fits into the guidelines.

    PEP-8:
    "While sometimes it’s okay to put an if/for/while with a small body on
    the same line, never do this for multi-clause statements.
    ...
    # Wrong:
    if foo == 'blah': do_blah_thing()
    for x in lst: total += x
    while t < 10: t = delay()
    "

    If the one-liner were not in a multi-statement block, it would be all
    right with PEP-8. OTOH, there is nothing that says one has to fully
    comply with PEP-8. I personally tend to use

    if test: return

    even inside larger blocks. If one is working with other someone else's
    project and there is a style guide, it's important to follow that guide
    because the other people involved will find it easier to read and
    understand your code.

    If you are working on your own project, PEP-8 is always a good starting
    point, and flake8 and pylint will be happier. That's worth something.

    On 12/14/2022 11:35 PM, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]> 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.

    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From dn@21:1/5 to Aaron P on Thu Dec 15 18:24:15 2022
    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

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Chris Angelico@21:1/5 to Thomas Passin on Thu Dec 15 17:56:08 2022
    On Thu, 15 Dec 2022 at 16:29, Thomas Passin <[email protected]> wrote:

    PEP-8, which is Guido's style guide and generally good to follow, does
    not completely discourage single-line usage like the example. It's not
    clear to me how Chris's example fits into the guidelines.

    PEP-8:
    "While sometimes it’s okay to put an if/for/while with a small body on
    the same line, never do this for multi-clause statements.
    ...
    # Wrong:
    if foo == 'blah': do_blah_thing()
    for x in lst: total += x
    while t < 10: t = delay()
    "

    If the one-liner were not in a multi-statement block, it would be all
    right with PEP-8.

    Not sure what your point is about it being "in" a multi-statement
    block - PEP 8 has nothing to say about that. What it's saying is that
    you shouldn't do this:

    if foo == 'blah': one(); two(); three()

    And I agree; if you're putting more than one statement after your
    'if', it's generally clearest to have it on multiple lines. But a
    simple "continue" or "break" statement works just fine on the same
    line as the if.

    ChrisA

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From [email protected]@21:1/5 to Aaron P on Thu Dec 15 01:58:11 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=[email protected]> On Behalf Of dn
    Sent: Thursday, December 15, 2022 12:24 AM
    To: [email protected]
    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

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Chris Green@21:1/5 to Thomas Passin on Thu Dec 15 08:58:26 2022
    Thomas Passin <[email protected]> wrote:
    I personally tend to use

    if test: return

    even inside larger blocks.

    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    "No multiple returns" is often found in programming guidelines.

    --
    Chris Green
    ·

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Chris Green on Thu Dec 15 12:41:54 2022
    Chris Green <[email protected]> writes:
    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    This "complexity" could also mean that the function has
    become too large. In such a case, one could say that the
    /size/ of the function is the actual cause of problems
    and not multiple returns.

    |Fools ignore complexity. Pragmatists suffer it. Some can
    |avoid it. Geniuses remove it.
    Alan Perlis (1922/1990)

    Within a small function, multiple returns are rarely
    a problem.

    When a function is large, one can apply well-known
    refactors. For an example, look at the code in the
    first post of the thread

    Python script not letting go of files
    Date: Tue, 29 Nov 2022 12:52:15 +0000

    and then at my reply of

    29 Nov 2022 14:44:39 GMT.

    "No multiple returns" is often found in programming guidelines.

    I religiously followed that when I did more C programming
    than today. Then, I read an article about how the result
    pattern makes functions measurably slower. (It should not
    with an optimizing compiler, but it did due to those
    measurements. Can't find that article now, though.)

    "Result pattern" I call writing,

    if a:
    result = 123
    else:
    result = 456
    return result

    , instead of,

    if a:
    return 123
    else
    return 456

    .

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Cecil Westerhof@21:1/5 to Stefan Ram on Thu Dec 15 14:09:54 2022
    [email protected] (Stefan Ram) writes:

    "No multiple returns" is often found in programming guidelines.

    I religiously followed that when I did more C programming
    than today. Then, I read an article about how the result
    pattern makes functions measurably slower. (It should not
    with an optimizing compiler, but it did due to those
    measurements. Can't find that article now, though.)

    That makes me think about the quote from Edsger W. Dijkstra about the
    go to statement:
    Please do not fall into the trap of believing that I am terribly
    dogmatic about the go to statement. I have the uncomfortable
    feeling that others are making a religion out of it, as if the
    conceptual problems of programming could be solved by a simple
    trick, by a simple form of coding discipline!

    --
    Cecil Westerhof
    Senior Software Engineer
    LinkedIn: http://www.linkedin.com/in/cecilwesterhof

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From [email protected]@21:1/5 to Chris Green on Thu Dec 15 14:05:32 2022
    Multiple returns is not always a problem as it depends on the nature of a
    task whether it has complex enough cases.

    I have seen code that instead sets Boolean variables when it is ready to
    return and everything else keeps checking the variables to skip further processing so the program then slides down to a single return statement. If done properly, it boils down to the same result if VERY carefully done but
    with lots of sometimes complex IF statements that may be not be updated well
    if the logic changes a bit.

    In such cases, I vastly prefer clean and unambiguous returns from the
    function right at the point where the decision is made, UNLESS the exit is
    not always clean as there may be cleanup or finalization of some kind
    required that is best done at a single point.

    If efficiency is an issue, then clearly a rapid exit may beat one where processing continues for a while and also often beats a method that involves creating and calling multiple smaller functions with lots of overhead.

    Having said all that, of course, if you can find a fairly simple algorithm
    that only returns from one place, use it instead of a convoluted one. The
    issue is not necessarily that multiple return points are bad, but that they
    are often a symptom of sloppy planning. But for some problems, they fit well and simplify things.

    -----Original Message-----
    From: Python-list <python-list-bounces+avi.e.gross=[email protected]> On Behalf Of Stefan Ram
    Sent: Thursday, December 15, 2022 7:42 AM
    To: [email protected]
    Subject: Re: Single line if statement with a continue

    Chris Green <[email protected]> writes:
    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    This "complexity" could also mean that the function has
    become too large. In such a case, one could say that the
    /size/ of the function is the actual cause of problems
    and not multiple returns.

    |Fools ignore complexity. Pragmatists suffer it. Some can avoid it.
    |Geniuses remove it.
    Alan Perlis (1922/1990)

    Within a small function, multiple returns are rarely
    a problem.

    When a function is large, one can apply well-known
    refactors. For an example, look at the code in the
    first post of the thread

    Python script not letting go of files
    Date: Tue, 29 Nov 2022 12:52:15 +0000

    and then at my reply of

    29 Nov 2022 14:44:39 GMT.

    "No multiple returns" is often found in programming guidelines.

    I religiously followed that when I did more C programming
    than today. Then, I read an article about how the result
    pattern makes functions measurably slower. (It should not
    with an optimizing compiler, but it did due to those
    measurements. Can't find that article now, though.)

    "Result pattern" I call writing,

    if a:
    result = 123
    else:
    result = 456
    return result

    , instead of,

    if a:
    return 123
    else
    return 456

    .


    --
    https://mail.python.org/mailman/listinfo/python-list

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From MRAB@21:1/5 to [email protected] on Thu Dec 15 19:34:28 2022
    On 2022-12-15 19:05, [email protected] wrote:
    Multiple returns is not always a problem as it depends on the nature of a task whether it has complex enough cases.

    I have seen code that instead sets Boolean variables when it is ready to return and everything else keeps checking the variables to skip further processing so the program then slides down to a single return statement. If done properly, it boils down to the same result if VERY carefully done but with lots of sometimes complex IF statements that may be not be updated well if the logic changes a bit.

    In such cases, I vastly prefer clean and unambiguous returns from the function right at the point where the decision is made, UNLESS the exit is not always clean as there may be cleanup or finalization of some kind required that is best done at a single point.

    A problem with having a single return is that it can lead to excessive indentation:

    if test_1:
    ...

    if test_2:
    ...

    if test_3:
    ...

    return

    With multiple returns, however:

    if not test_1:
    return

    ...

    if not test_2:
    return

    ...

    if not test_3:
    return

    ...

    return

    If efficiency is an issue, then clearly a rapid exit may beat one where processing continues for a while and also often beats a method that involves creating and calling multiple smaller functions with lots of overhead.

    Having said all that, of course, if you can find a fairly simple algorithm that only returns from one place, use it instead of a convoluted one. The issue is not necessarily that multiple return points are bad, but that they are often a symptom of sloppy planning. But for some problems, they fit well and simplify things.

    -----Original Message-----
    From: Python-list <python-list-bounces+avi.e.gross=[email protected]> On Behalf Of Stefan Ram
    Sent: Thursday, December 15, 2022 7:42 AM
    To: [email protected]
    Subject: Re: Single line if statement with a continue

    Chris Green <[email protected]> writes:
    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    This "complexity" could also mean that the function has
    become too large. In such a case, one could say that the
    /size/ of the function is the actual cause of problems
    and not multiple returns.

    |Fools ignore complexity. Pragmatists suffer it. Some can avoid it.
    |Geniuses remove it.
    Alan Perlis (1922/1990)

    Within a small function, multiple returns are rarely
    a problem.

    When a function is large, one can apply well-known
    refactors. For an example, look at the code in the
    first post of the thread

    Python script not letting go of files
    Date: Tue, 29 Nov 2022 12:52:15 +0000

    and then at my reply of

    29 Nov 2022 14:44:39 GMT.

    "No multiple returns" is often found in programming guidelines.

    I religiously followed that when I did more C programming
    than today. Then, I read an article about how the result
    pattern makes functions measurably slower. (It should not
    with an optimizing compiler, but it did due to those
    measurements. Can't find that article now, though.)

    "Result pattern" I call writing,

    if a:
    result = 123
    else:
    result = 456
    return result

    , instead of,

    if a:
    return 123
    else
    return 456

    .


    --
    https://mail.python.org/mailman/listinfo/python-list


    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Weatherby,Gerard@21:1/5 to Chris Green on Thu Dec 15 19:22:59 2022
    I once saw a C function full of GOTOs which jumped to the return state at the bottom of the functions because the programmer had learned that �multiple returns are a bad idea.�

    I totally agree multiple returns causing confusion is a symptom of poor design, not a cause.

    Required cleanup is easily handled by the try / finally construct.

    From: Python-list <python-list-bounces+gweatherby=[email protected]> on behalf of [email protected] <[email protected]>
    Date: Thursday, December 15, 2022 at 2:07 PM
    To: [email protected] <[email protected]>
    Subject: RE: Single line if statement with a continue
    *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

    Multiple returns is not always a problem as it depends on the nature of a
    task whether it has complex enough cases.

    I have seen code that instead sets Boolean variables when it is ready to
    return and everything else keeps checking the variables to skip further processing so the program then slides down to a single return statement. If done properly, it boils down to the same result if VERY carefully done but
    with lots of sometimes complex IF statements that may be not be updated well
    if the logic changes a bit.

    In such cases, I vastly prefer clean and unambiguous returns from the
    function right at the point where the decision is made, UNLESS the exit is
    not always clean as there may be cleanup or finalization of some kind
    required that is best done at a single point.

    If efficiency is an issue, then clearly a rapid exit may beat one where processing continues for a while and also often beats a method that involves creating and calling multiple smaller functions with lots of overhead.

    Having said all that, of course, if you can find a fairly simple algorithm
    that only returns from one place, use it instead of a convoluted one. The
    issue is not necessarily that multiple return points are bad, but that they
    are often a symptom of sloppy planning. But for some problems, they fit well and simplify things.

    -----Original Message-----
    From: Python-list <python-list-bounces+avi.e.gross=[email protected]> On Behalf Of Stefan Ram
    Sent: Thursday, December 15, 2022 7:42 AM
    To: [email protected]
    Subject: Re: Single line if statement with a continue

    Chris Green <[email protected]> writes:
    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    This "complexity" could also mean that the function has
    become too large. In such a case, one could say that the
    /size/ of the function is the actual cause of problems
    and not multiple returns.

    |Fools ignore complexity. Pragmatists suffer it. Some can avoid it.
    |Geniuses remove it.
    Alan Perlis (1922/1990)

    Within a small function, multiple returns are rarely
    a problem.

    When a function is large, one can apply well-known
    refactors. For an example, look at the code in the
    first post of the thread

    Python script not letting go of files
    Date: Tue, 29 Nov 2022 12:52:15 +0000

    and then at my reply of

    29 Nov 2022 14:44:39 GMT.

    "No multiple returns" is often found in programming guidelines.

    I religiously followed that when I did more C programming
    than today. Then, I read an article about how the result
    pattern makes functions measurably slower. (It should not
    with an optimizing compiler, but it did due to those
    measurements. Can't find that article now, though.)

    "Result pattern" I call writing,

    if a:
    result = 123
    else:
    result = 456
    return result

    , instead of,

    if a:
    return 123
    else
    return 456

    .


    -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/
    python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$>

    -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/
    python-list__;!!Cn_UX_p3!lVeLOl91qPUjowC1ch_u353upn8X-V4rsReaNberWpIXBlBP6CYcDgr_aaMb0ZHoYX4YWO8id1biCn6sW7V6vJM$>

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to MRAB on Thu Dec 15 19:49:08 2022
    MRAB <[email protected]> writes:
    A problem with having a single return is that it can lead to excessive >indentation:
    if test_1:
    ...
    if test_2:
    ...
    if test_3:
    ...
    return

    Refactoring is fun with executable code, no fun with vague
    pseudo code. Therefore, I have chosen not to refactor the
    vague pseudo code from above. Instead I'd like to recommend
    to look at the code in the first post of the thread

    Python script not letting go of files
    Date: Tue, 29 Nov 2022 12:52:15 +0000

    and then at my reply of

    29 Nov 2022 14:44:39 GMT.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Thomas Passin@21:1/5 to Chris Green on Thu Dec 15 14:56:03 2022
    On 12/15/2022 3:58 AM, Chris Green wrote:
    Thomas Passin <[email protected]> wrote:
    I personally tend to use

    if test: return

    even inside larger blocks.

    I always try to avoid multiple returns from functions/methods, as soon
    as things get complex it's all to easy to miss clean-up etc.

    "No multiple returns" is often found in programming guidelines.

    Yes, or alternatively, "If any branch uses a return, they all should."

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Grant Edwards@21:1/5 to MRAB on Thu Dec 15 13:34:54 2022
    On 2022-12-15, MRAB <[email protected]> wrote:

    A problem with having a single return is that it can lead to excessive indentation:

    if test_1:
    ...

    if test_2:
    ...

    if test_3:
    ...

    return

    I sometimes have to work on code like that with bocks nested 8-10
    levels deep spread out over hundreds of lines. The first thing I do is
    convert it to something like the code below. Check for error
    conditions up front and exit accordingly.

    When working in C, a "goto error" or "goto done" instead of "return"
    can provide a "single return" if that's deemed important.


    With multiple returns, however:

    if not test_1:
    return

    ...

    if not test_2:
    return

    ...

    if not test_3:
    return

    ...

    return

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Rob Cliffe@21:1/5 to Chris Angelico on Thu Dec 15 13:30:39 2022
    On 15/12/2022 04:35, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]> 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.


    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA
    I'm so glad that Chris and others say this.  It (i.e. if plus break/continue/return on a single line) is something I have quite often
    done in my own code, albeit with a feeling of guilt that I was breaking
    a Python taboo.  Now I will do it with a clear conscience. 😁
    Best wishes
    Rob Cliffe

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Abdullah Nafees@21:1/5 to [email protected] on Sun Dec 18 00:22:42 2022
    Just wanted to say that a silent reader like me learnt more about PEP-8
    solely from this thread than my mentor at work or any other course I have
    taken earlier this year. Thank you so much.

    On Sun, 18 Dec 2022, 00:16 Rob Cliffe via Python-list, < [email protected]> wrote:



    On 15/12/2022 04:35, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]>
    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.


    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA
    I'm so glad that Chris and others say this. It (i.e. if plus break/continue/return on a single line) is something I have quite often
    done in my own code, albeit with a feeling of guilt that I was breaking
    a Python taboo. Now I will do it with a clear conscience. 😁
    Best wishes
    Rob Cliffe
    --
    https://mail.python.org/mailman/listinfo/python-list


    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From dn@21:1/5 to Rob Cliffe via Python-list on Sun Dec 18 10:59:14 2022
    On 16/12/2022 02.30, Rob Cliffe via Python-list wrote:
    On 15/12/2022 04:35, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]>
    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.


    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA
    I'm so glad that Chris and others say this.  It (i.e. if plus break/continue/return on a single line) is something I have quite often
    done in my own code, albeit with a feeling of guilt that I was breaking
    a Python taboo.  Now I will do it with a clear conscience. 😁

    Anxiety doesn't help anyone - least of all you.

    Remember another Python mantra: "we're all adults here"!

    (also (compulsory interjection) PEP-008 is not a set of rules for all
    Python code - see PEP-008)

    --
    Regards,
    =dn

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From [email protected]@21:1/5 to Chris Angelico on Sat Dec 17 18:57:47 2022
    I happen to be of two schools here.

    Is something sort of taboo when using something like a computer language to write a program? What if another language tells you to do it a different way or sort of the opposite? Is it based on the details of the language and implementation or the
    prejudices of the one trying to make rules?

    If a compiler or interpreter HAPPILY (as happy as machines/code get) compiles or interprets your code without errors every time you use it a certain way, then it is not wrong to use it. Of course if it subject to change or already deprecated, ...

    If people around you complain they do not like it, then the word "taboo" does apply but you can feel free to re-educate them or move on.

    This reminds me too much of people who are taught some grammar such as some part of a sentence requiring a "noun-phrase" and later it explains that a non-phrase can be EITHER a noun accompanied by an assortment of other words that together form a phrase,
    or just a "noun" or just a "pronoun" or just a "nothing but an implied pronoun".

    So which is it? The answer is all of them are legal, at least within bounds. A sentence like "Come over here" is an implied "You come over here" and works best if earlier sentences have laid some context on what is being talked about so the "you" is
    obvious or will be explained later but perhaps should be discouraged in other circumstances.

    So back to computer languages. Many languages using grouping with something like "{...}" often do not care where you break your lines albeit some get touchy about an else statement placed improperly. It is perfectly legal to write:

    If (condition) { first; second; third }

    The grammar basically states that a "statement" or similar name can be a simple statement or a compound statement and anywhere one can go, within reason, so can the other.

    Python has a twist here in that they discourage or outlaw some such things as they use mainly indentation rather than braces. This makes it hard to use multiple lines when the first line is way at the end as the others do not line up. It becomes all or
    ONE. I mean it allows a simple expression on the same line after the colon and then terminates the construct so a future indented line is seen as an indentation error. An experiment shows the following attempt to line up a second line way over below the
    first also fails:

    if 5 > 3: a = a * 3
    b = b * 3

    In a constant width font my second line is indented so "b is just below "a" and it fails because the interpreter does not measure the beginning column of the first line as being where the " a = a * 3" starts but at the "if" and that makes reasonable
    sense. I could imagine another design but since it is not what is done, the multi-line version MUST be done only on subsequent lines indented properly and identically.

    So it is not really right or wrong to do one-liners. It is legal and often more readable. But if you ever want to extend your lines to be multi-line, it probably is best to use the multi-line approach regularly.

    Still, using many editors, you will rapidly notice something is wrong when adding a line of code and seeing it is indented under the "if".

    Is anyone really thrilled to read code in other languages that span so many lines:

    If (condition)
    {
    var1 = 0
    }
    else
    {
    var1 = 1
    }

    It is a great way to get your line-of-code count up but the many briefer versions can be easier to read in one glance up to and including a bit murkier ones like

    var1 = (condition) ? 0 : 1

    My view is that simple things that fit easily on a screen, and also held all at once in my mind, should be written fairly concisely. I do admit how much I can hold at once varies based on how well I can concentrate at that moment and have met people
    whose short-term memory for many things is larger or smaller than mine. But generally people can handle simple constructs like we are discussing.

    Complicated things and ones that might need changes later should be written very cautiously and in detail including judicious use of comments around and within the code OR consider re-planning it into a less complicated form that calls on other fairly
    simple functions that can each be decently understood based on naming and usage.

    If you have a complicated calculation that eventually assigns values to a1, a2, a3, a4 then a language like Python makes a
    One liner easy as in:

    If (condition):
    a1, a2, a3, a4 = func(args)

    But now that four or more lines have been collapsed into one, maybe something like this works too and maybe is a tad more readable with parentheses:

    If (condition): (a1, a2, a3, a4) = func(args)


    I am not suggesting using something silly like this though:

    if(1): (a, b, c, d) = (min(1,2), (1+2)/2, (1*2*2*3)/4, max(1,2))

    That is so way beyond a one liner that it is best seen as multiple lines. It may be legal but is best used to obfuscate!

    The problem with some RULES is that not only are they not real rules but sometimes have exceptions where they get in the way of getting things done.

    - Avi

    -----Original Message-----
    From: Python-list <python-list-bounces+avi.e.gross=[email protected]> On Behalf Of Rob Cliffe via Python-list
    Sent: Thursday, December 15, 2022 8:31 AM
    To: [email protected]
    Subject: Re: Single line if statement with a continue



    On 15/12/2022 04:35, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]> 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.


    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA
    I'm so glad that Chris and others say this. It (i.e. if plus break/continue/return on a single line) is something I have quite often done in my own code, albeit with a feeling of guilt that I was breaking a Python taboo. Now I will do it with a clear
    conscience. 😁
    Best wishes
    Rob Cliffe
    --
    https://mail.python.org/mailman/listinfo/python-list

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Thomas Passin@21:1/5 to [email protected] on Sat Dec 17 19:50:42 2022
    if 5 > 3: a = a * 3
    b = b * 3

    That would be a fairly weird construction, neither one thing nor
    another. But still, if you really want it that way, this is legal Python:

    a = 2; b = 10
    if 5 > 3: a = a * 3;\
    b = b * 3
    print(a, b) # 6 30

    On 12/17/2022 6:57 PM, [email protected] wrote:
    I happen to be of two schools here.

    Is something sort of taboo when using something like a computer language to write a program? What if another language tells you to do it a different way or sort of the opposite? Is it based on the details of the language and implementation or the
    prejudices of the one trying to make rules?

    If a compiler or interpreter HAPPILY (as happy as machines/code get) compiles or interprets your code without errors every time you use it a certain way, then it is not wrong to use it. Of course if it subject to change or already deprecated, ...

    That's not the point of using some consistent style. IMO, source code
    should be clear, compact, and easy for someone else to understand. That someone might be you six months from now.

    These objectives do not always align. Consistency helps reduce mental
    effort by using constructions and formatting in a familiar way -
    basically, using a familiar programming idiom. Compactness can help
    clarity, unless the code is too terse which can become a hindrance. But
    too much verbosity can get in the way of grasping the essential processing.

    Personal taste and familiarity also factor into assessing clarity and compactness.

    It's always a balancing act. Style guides can help by providing good
    basic idioms. There's no law** that says you *have* to follow them
    exactly all the time. But it's helpful when you can. If your own style
    guide i is similar to one used widely, so much the better.

    **Except at some organizations

    If people around you complain they do not like it, then the word "taboo" does apply but you can feel free to re-educate them or move on.

    This reminds me too much of people who are taught some grammar such as some part of a sentence requiring a "noun-phrase" and later it explains that a non-phrase can be EITHER a noun accompanied by an assortment of other words that together form a
    phrase, or just a "noun" or just a "pronoun" or just a "nothing but an implied pronoun".

    So which is it? The answer is all of them are legal, at least within bounds. A sentence like "Come over here" is an implied "You come over here" and works best if earlier sentences have laid some context on what is being talked about so the "you" is
    obvious or will be explained later but perhaps should be discouraged in other circumstances.

    So back to computer languages. Many languages using grouping with something like "{...}" often do not care where you break your lines albeit some get touchy about an else statement placed improperly. It is perfectly legal to write:

    If (condition) { first; second; third }

    The grammar basically states that a "statement" or similar name can be a simple statement or a compound statement and anywhere one can go, within reason, so can the other.

    Python has a twist here in that they discourage or outlaw some such things as they use mainly indentation rather than braces. This makes it hard to use multiple lines when the first line is way at the end as the others do not line up. It becomes all or
    ONE. I mean it allows a simple expression on the same line after the colon and then terminates the construct so a future indented line is seen as an indentation error. An experiment shows the following attempt to line up a second line way over below the
    first also fails:

    if 5 > 3: a = a * 3
    b = b * 3

    In a constant width font my second line is indented so "b is just below "a" and it fails because the interpreter does not measure the beginning column of the first line as being where the " a = a * 3" starts but at the "if" and that makes reasonable
    sense. I could imagine another design but since it is not what is done, the multi-line version MUST be done only on subsequent lines indented properly and identically.

    So it is not really right or wrong to do one-liners. It is legal and often more readable. But if you ever want to extend your lines to be multi-line, it probably is best to use the multi-line approach regularly.

    Still, using many editors, you will rapidly notice something is wrong when adding a line of code and seeing it is indented under the "if".

    Is anyone really thrilled to read code in other languages that span so many lines:

    If (condition)
    {
    var1 = 0
    }
    else
    {
    var1 = 1
    }

    It is a great way to get your line-of-code count up but the many briefer versions can be easier to read in one glance up to and including a bit murkier ones like

    var1 = (condition) ? 0 : 1

    My view is that simple things that fit easily on a screen, and also held all at once in my mind, should be written fairly concisely. I do admit how much I can hold at once varies based on how well I can concentrate at that moment and have met people
    whose short-term memory for many things is larger or smaller than mine. But generally people can handle simple constructs like we are discussing.

    Complicated things and ones that might need changes later should be written very cautiously and in detail including judicious use of comments around and within the code OR consider re-planning it into a less complicated form that calls on other fairly
    simple functions that can each be decently understood based on naming and usage.

    If you have a complicated calculation that eventually assigns values to a1, a2, a3, a4 then a language like Python makes a
    One liner easy as in:

    If (condition):
    a1, a2, a3, a4 = func(args)

    But now that four or more lines have been collapsed into one, maybe something like this works too and maybe is a tad more readable with parentheses:

    If (condition): (a1, a2, a3, a4) = func(args)


    I am not suggesting using something silly like this though:

    if(1): (a, b, c, d) = (min(1,2), (1+2)/2, (1*2*2*3)/4, max(1,2))

    That is so way beyond a one liner that it is best seen as multiple lines. It may be legal but is best used to obfuscate!

    The problem with some RULES is that not only are they not real rules but sometimes have exceptions where they get in the way of getting things done.

    - Avi

    -----Original Message-----
    From: Python-list <python-list-bounces+avi.e.gross=[email protected]> On Behalf Of Rob Cliffe via Python-list
    Sent: Thursday, December 15, 2022 8:31 AM
    To: [email protected]
    Subject: Re: Single line if statement with a continue



    On 15/12/2022 04:35, Chris Angelico wrote:
    On Thu, 15 Dec 2022 at 14:41, Aaron P <[email protected]> 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.


    Nothing at all wrong with writing that on a single line. If you have
    issues with Flake8 not accepting your choices, reconfigure Flake8 :)

    ChrisA
    I'm so glad that Chris and others say this. It (i.e. if plus break/continue/return on a single line) is something I have quite often done in my own code, albeit with a feeling of guilt that I was breaking a Python taboo. Now I will do it with a clear
    conscience. 😁
    Best wishes
    Rob Cliffe
    --
    https://mail.python.org/mailman/listinfo/python-list


    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Chris Angelico@21:1/5 to [email protected] on Sun Dec 18 11:59:44 2022
    On Sun, 18 Dec 2022 at 10:59, <[email protected]> wrote:

    If a compiler or interpreter HAPPILY (as happy as machines/code get) compiles or interprets your code without errors every time you use it a certain way, then it is not wrong to use it. Of course if it subject to change or already deprecated, ...


    Source code is, first and foremost, for programmers to read. You're
    confusing it with binary executables.

    ChrisA

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Dennis Lee Bieber@21:1/5 to All on Sun Dec 18 11:07:18 2022
    On Wed, 14 Dec 2022 10:53:10 -0800 (PST), Aaron P
    <[email protected]> declaimed the following:

    Late response here, and the concept may have been covered in skimmed-over posts..

    I occasionally run across something like:

    for idx, thing in enumerate(things):
    if idx == 103:
    continue
    do_something_with(thing)


    For this example, I'd probably reverse the condition.

    if idx != 103:
    do_something_with(thing)

    and hence completely drop the "continue" -- after all, if idx is 103, the
    if statement falls through, and the end of the loop acts as an implicit "continue"

    OTOH: if the "if/continue" is buried in four or five layers of conditionals, it could be cleaner than trying to configure the conditionals
    to have a chained exit.


    --
    Wulfraed Dennis Lee Bieber AF6VN
    [email protected] http://wlfraed.microdiversity.freeddns.org/

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Stefan Ram@21:1/5 to Dennis Lee Bieber on Sun Dec 18 16:49:27 2022
    Dennis Lee Bieber <[email protected]> writes:
    for idx, thing in enumerate(things):
    if idx == 103:
    continue
    do_something_with(thing)

    For this example, I'd probably reverse the condition.
    if idx != 103:
    do_something_with(thing)

    The first four lines of the quotation above cannot be a
    complete program as "do_something_with" is not defined
    therein, so they must be part of a larger program.
    If, in this larger program, something still follows
    "do_something_with(thing)" in the loop, the new program
    after the transformation might not show the same behavior.

    def do_something_with( what ):
    print( what )

    for i in range( 3 ):
    thing = "it"
    if i == 2:
    continue
    do_something_with( thing )
    print( "B" )

    print()

    for i in range( 3 ):
    thing = "it"
    if i != 2:
    do_something_with( thing )
    print( "B" )

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Tony Oliver@21:1/5 to [email protected] on Sun Dec 18 13:27:52 2022
    On Saturday, 17 December 2022 at 23:58:11 UTC, [email protected] wrote:
    Is something sort of taboo when using something like a computer language to write a program?

    With what else would you write a program?

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Peter J. Holzer@21:1/5 to Stefan Ram on Mon Dec 19 13:01:41 2022
    On 2022-12-18 16:49:27 +0000, Stefan Ram wrote:
    Dennis Lee Bieber <[email protected]> writes:
    for idx, thing in enumerate(things):
    if idx == 103:
    continue
    do_something_with(thing)

    For this example, I'd probably reverse the condition.
    if idx != 103:
    do_something_with(thing)

    The first four lines of the quotation above cannot be a
    complete program as "do_something_with" is not defined
    therein, so they must be part of a larger program.
    If, in this larger program, something still follows
    "do_something_with(thing)" in the loop, the new program
    after the transformation might not show the same behavior.

    “do_something_with(thing)” is obviously not intended to be a single function call but as a shorthand for “one or more lines of code which do something with `thing`”. So there is nothing after it because it is
    included in it.

    That said, the "fail and bail" technique is often more readable than
    putting the main incode inside of an if - especially if that code is
    long and/or it is guarded by multiple conditions.

    hp

    --
    _ | Peter J. Holzer | Story must make more sense than reality.
    |_|_) | |
    | | | [email protected] | -- Charles Stross, "Creative writing
    __/ | http://www.hjp.at/ | challenge!"

    -----BEGIN PGP SIGNATURE-----

    iQIzBAABCgAdFiEETtJbRjyPwVTYGJ5k8g5IURL+KF0FAmOgUqAACgkQ8g5IURL+ KF0EjhAAhg07qSXPh6hrK5yEk7xKd9qKwrByaQbm6v8YZ+Rg5n13MwWtjkX2ISnm taIEgLfTCHozylzaVk5Yy9srmCHReyH1Swt9+c5HL8fKmzDHYBUmNxER5sdt9zwS 8jip2lBUWgRZKUc8cjbywaJQOrP6SxfBzB2iZ2hoHMFeYECBdsTNbiPUyitPXxrG SQOYuQBL5DaIdHweaVabLqhK45uGVU2gZt+bKU64mQX0tfO5HMb8KXIjnQryf2D0 JaTb1JD6Rqbg5+DiegVvapz1TBkPaxzExFpuow9VfAwikO089vUo46u4q8gSl7rG CQuGp/ZWdkf0A10t+vxSV7daep2loUZmz3Z0tWBo+u+NlyaySNqZ7Ou04+ENW57A xPqeXPZ226PKC0OBfc0rFk8hAgg9JkGTGjvQPOePq/Fw0AwEV5FNLyC/1wHQ0PL9 ueNQU+oHbdOOlGvBsBUyguYZI192XufQibRSyI3oLbUYM5G9BFB45d/oDsRlMM7D m4+tffH8sAmNKwmHuQsk8pVbFM7j9rgN3xpKMfq+/PU5zmq1d2vivwXZMnT7XQBB aAELgFzfMIk9iqoq0+jxIIr4dyOxLvhvpziwLbhLGE1lB3yYb1OhrsV6Z1AYH61K 68tFYwUYG/UEwDAmMOF+l8B5HC1livXST8Spvk5