Line continuation and comments

Thomas Passin list1 at tompassin.net
Wed Feb 22 11:27:09 EST 2023


On 2/22/2023 10:02 AM, Weatherby,Gerard wrote:
> That’s a neat tip. End of line comments work, too
> 
> x = (3 > 4  #never
>       and 7 == 7  # hopefully
>       or datetime.datetime.now().day > 15 # sometimes
>       )
> print(x)

I find myself doing this more and more often.  It can also help to make 
the code more readable and the intention more clear. Here's one example:

     return (getTerminalFromProcess()
             or getTerminalFromDirectory('/usr/bin')
             or getTerminalFromDirectory('/bin')
             or getCommonTerminal(('konsole', 'xterm'))
             )

It's easier to read than using a "\" at the end of lines, writing it all 
on one line would make for an unreadably long line, while building up 
the final result in steps would make the logic less clear.


> From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Edmondo Giovannozzi <edmondo.giovannozzi at gmail.com>
> Date: Wednesday, February 22, 2023 at 9:40 AM
> To: python-list at python.org <python-list at python.org>
> Subject: Re: Line continuation and comments
> *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***
> 
> Il giorno mercoledì 22 febbraio 2023 alle 09:50:14 UTC+1 Robert Latest ha scritto:
>> I found myself building a complicated logical condition with many ands and ors
>> which I made more manageable by putting the various terms on individual lines
>> and breaking them with the "\" line continuation character. In this context it
>> would have been nice to be able to add comments to lines terms which of course
>> isn't possible because the backslash must be the last character on the line.
>>
>> Question: If the Python syntax were changed to allow comments after line-ending
>> backslashes, would it break any existing code? I can't think of an example.
> 
> Well you can if you use parenthesis like in:
> x = 5
> a = (x > 3 and
> #     x < 21 or
>       x > 100
>       )
> You don't need the "\" to continue a line in this case
> 
> --
> https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kck9yP0ubC7L_tbIUoMY-nkZJlkXFAiZdnjPtekuYQXN6F8K2wFMW5lO1xZ6gYv6vDdsSo5jxy1QYU_T-EgHsOJ6x7TvXQ$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kck9yP0ubC7L_tbIUoMY-nkZJlkXFAiZdnjPtekuYQXN6F8K2wFMW5lO1xZ6gYv6vDdsSo5jxy1QYU_T-EgHsOJ6x7TvXQ$>



More information about the Python-list mailing list