Mailing List Archive

Line continuation and comments
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.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
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://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
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)

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Edmondo Giovannozzi <edmondo.giovannozzi@gmail.com>
Date: Wednesday, February 22, 2023 at 9:40 AM
To: python-list@python.org <python-list@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$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Adding to this, there should be no reason now in recent versions of
Python to ever use line continuation. Black goes so far as to state
"backslashes are bad and should never be used":

https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html#using-backslashes-for-with-statements

On Wed, 2023-02-22 at 01:24 -0800, Edmondo Giovannozzi wrote:
> 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://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
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@python.org> on behalf of Edmondo Giovannozzi <edmondo.giovannozzi@gmail.com>
> Date: Wednesday, February 22, 2023 at 9:40 AM
> To: python-list@python.org <python-list@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$>

--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 22/02/2023 15:23, Paul Bryan wrote:
> Adding to this, there should be no reason now in recent versions of
> Python to ever use line continuation. Black goes so far as to state
> "backslashes are bad and should never be used":
>
> https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html#using-backslashes-for-with-statements

def someFunc():
    HelpText = """\
Left click:             Open spam
Shift + Left click:     Cook spam
Right click:            Crack egg
Shift + Right click:    Fry egg
"""

The initial backslash aligns the first line with the others (in a fixed
font of course).
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 22Feb2023 11:27, Thomas Passin <list1@tompassin.net> wrote:
>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'))
> )

Aye, me too.

I autoformat my code using `yapf` (I _hate_ `black`) and append my
personal code style below. In particular, note the
`split_before_logical_operator` which does the above automatically when
it reflows a logical expression (you need the brackets, but you need
them anyway for multiline stuff if you're eschewing the backslash).

[style]
based_on_style = pep8
align_closing_bracket_with_visual_indent = True
arithmetic_precedence_indication = False
blank_line_before_module_docstring = True
blank_line_before_nested_class_or_def = True
blank_lines_around_top_level_definition = 1
dedent_closing_brackets = True
indent_dictionary_value = False
indent_width = 2
space_between_ending_comma_and_closing_bracket = False
spaces_before_comment = 2
split_before_dot = True
split_before_expression_after_opening_paren = True
split_before_first_argument = True
split_before_logical_operator = True
split_complex_comprehension = True
use_tabs = False

So basicly PEP8 with some tweaks.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
RE: Line continuation and comments [ In reply to ]
Good example, Rob, of how some people make what I consider RELIGIOUS edicts that one can easily violate if one wishes and it makes lots of sense in your example.

Let me extend that. The goal was to store a character string consisting of multiple lines when printed that are all left-aligned. Had you written:

HelpText = """
Left click: Open spam
...
Shift + Right click: Fry egg
"""
Then it would begin with an extra carriage return you did not want. Your example also ends with a carriage return because you closed the quotes on another line, so a \ on the last line of text (or moving the quotes to the end of the line) would be a way of avoiding that.

Consider some alternatives I have seen that are in a sense ugly and may involve extra work for the interpreter unless it is byte compiled once.

def someFunc():
HelpText =
"Left click: Open spam" + "\n" +
"Shift + Left click: Cook spam" + "\n" +
...

Or the variant of:
HelpText = "Left click: Open spam\n"
HelpText += " Shift + Left click: Cook spam\n"
...

Or perhaps just dumping the multi-line text into a file beforehand and reading that into a string!

def someFunc():

The backslash is not looking like such a bad idea! LOL!

-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Rob Cliffe via Python-list
Sent: Wednesday, February 22, 2023 2:08 PM
To: python-list@python.org
Subject: Re: Line continuation and comments



On 22/02/2023 15:23, Paul Bryan wrote:
> Adding to this, there should be no reason now in recent versions of
> Python to ever use line continuation. Black goes so far as to state
> "backslashes are bad and should never be used":
>
> https://black.readthedocs.io/en/stable/the_black_code_style/future_sty
> le.html#using-backslashes-for-with-statements

def someFunc():
HelpText = """\
Left click: Open spam
Shift + Left click: Cook spam
Right click: Crack egg
Shift + Right click: Fry egg
"""

The initial backslash aligns the first line with the others (in a fixed font of course).
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list

--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 22/02/2023 21.49, Robert Latest via Python-list wrote:
> 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.

Alternative to suggestions thus far: break the complex* logical
condition into 'labelled' components, and then combine those (likely
shorter) into the condition:

if person.is_adult and person.is_qualified and person.has_funds ...

which presumes that at some previous time we have, for example:

def is_adult( self )->bool:
return 21 <= self.age <= 65

(not that I'd like to see those two 'magic-constants' in anyone's code,
but (hopefully) the idea has been conveyed...)


* "simple is better than..."

NB my PyCharm-settings grumble whenever I create an identifier which is
only used once (and perhaps, soon after it was established). I
understand the (space) optimisation, but prefer to trade that for
'readability'.
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
?
NB my PyCharm-settings grumble whenever I create an identifier which is
only used once (and perhaps, soon after it was established). I
understand the (space) optimisation, but prefer to trade that for
'readability'.
?
I haven?t seen that one. What I get is warnings about:

def is_adult( self )->bool:
LEGAL_AGE_US = 21
return LEGAL_AGE

It doesn?t like LEGAL_AGE_US being all caps if declared in a function.

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of dn via Python-list <python-list@python.org>
Date: Thursday, February 23, 2023 at 5:46 PM
To: python-list@python.org <python-list@python.org>
Subject: Re: Line continuation and comments
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On 22/02/2023 21.49, Robert Latest via Python-list wrote:
> 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.

Alternative to suggestions thus far: break the complex* logical
condition into 'labelled' components, and then combine those (likely
shorter) into the condition:

if person.is_adult and person.is_qualified and person.has_funds ...

which presumes that at some previous time we have, for example:

def is_adult( self )->bool:
return 21 <= self.age <= 65

(not that I'd like to see those two 'magic-constants' in anyone's code,
but (hopefully) the idea has been conveyed...)


* "simple is better than..."

NB my PyCharm-settings grumble whenever I create an identifier which is
only used once (and perhaps, soon after it was established). I
understand the (space) optimisation, but prefer to trade that for
'readability'.
--
Regards,
=dn
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ghW7FUX8GJF79keLaMyaVewXcKw3jexuxF-QJh8h564QBAIoi2ez20tIl5fg762Rcfnh-XA4sG53CKt2NYgHpTWlyA$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ghW7FUX8GJF79keLaMyaVewXcKw3jexuxF-QJh8h564QBAIoi2ez20tIl5fg762Rcfnh-XA4sG53CKt2NYgHpTWlyA$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 24/02/2023 12.45, Weatherby,Gerard wrote:
> “
> NB my PyCharm-settings grumble whenever I create an identifier which is
> only used once (and perhaps, soon after it was established). I
> understand the (space) optimisation, but prefer to trade that for
> 'readability'.
> “
>
> I haven’t seen that one. What I get is warnings about:
>
> def is_adult( self )->bool:
>     LEGAL_AGE_US = 21
>     return LEGAL_AGE
>
> It doesn’t like LEGAL_AGE_US being all caps if declared in a function.

Yes, I suffered this one too.

The rationale comes from PEP-008 (Constants):

Constants are usually defined on a module level and written in all
capital letters with underscores separating words.


Today, I wasn't criticised for:
> NB my PyCharm-settings grumble whenever I create an identifier which is
> only used once (and perhaps, soon after it was established). I
> understand the (space) optimisation, but prefer to trade that for
> 'readability'.

Perhaps that came from AWS CodeWhisperer which I have since abandoned,
or maybe from SonarLint (which I've just checked to discover it is not
working properly...)

--
Regards,
=dn

--
https://mail.python.org/mailman/listinfo/python-list
RE: Line continuation and comments [ In reply to ]
Many "warnings" can safely be ignored.

The function as shown does not look right. I assume it is just an example, but a function that ignores the argument supplied is already a tad suspect.

Since it is SUGGESTED that the variable name "self" normally is used in a method for a class/instance, it is of course possible for it to set a variable called LEGAL_AGE_US to 21 and for no special reason, returns the age.

But my imagination is that a function called is_adult() should perhaps receive an age either as an argument, or an attribute of the current object and return True only if that age is greater than or equal to the legal age. Of course LEGAL_AGE_US may suggest a family of such functions specifying a legal age threshold for various countries or regions and all you need is the age between non-adult and adult.

So one GUESS I have is that if this is a method, then you are seen not as setting a constant inside the function, where all-caps might be sensible but as setting an instance variable or changing it. A true constant might have been set when the class was designed or perhaps in __init__() or similar.

I wonder how PyCharm would react if you used:

self.LEGAL_AGE_US = 21



-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of dn via Python-list
Sent: Thursday, February 23, 2023 9:01 PM
To: python-list@python.org
Subject: Re: Line continuation and comments

On 24/02/2023 12.45, Weatherby,Gerard wrote:
> “
> NB my PyCharm-settings grumble whenever I create an identifier which
> is only used once (and perhaps, soon after it was established). I
> understand the (space) optimisation, but prefer to trade that for
> 'readability'.
> “
>
> I haven’t seen that one. What I get is warnings about:
>
> def is_adult( self )->bool:
> LEGAL_AGE_US = 21
> return LEGAL_AGE
>
> It doesn’t like LEGAL_AGE_US being all caps if declared in a function.

Yes, I suffered this one too.

The rationale comes from PEP-008 (Constants):

Constants are usually defined on a module level and written in all capital letters with underscores separating words.


Today, I wasn't criticised for:
> NB my PyCharm-settings grumble whenever I create an identifier which is
> only used once (and perhaps, soon after it was established). I
> understand the (space) optimisation, but prefer to trade that for
> 'readability'.

Perhaps that came from AWS CodeWhisperer which I have since abandoned,
or maybe from SonarLint (which I've just checked to discover it is not
working properly...)

--
Regards,
=dn

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

--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 24/02/2023 12.45, Weatherby,Gerard wrote:
>>NB my PyCharm-settings grumble whenever I create an identifier which
>>is
>>only used once (and perhaps, soon after it was established). I
>>understand the (space) optimisation, but prefer to trade that for
>>'readability'.

It isn't "space". Got an example for that warning? I don't use PyCharm,
but the main linter warning I get is an _unused_ variable, eg:

def f():
x = 3

I set x and never use it. Likely brain fade on my part, and worth a
warning.

On 24Feb2023 15:01, dn <PythonList@DancesWithMice.info> wrote:
>>I haven’t seen that one. What I get is warnings about:
>>
>>def is_adult( self )->bool:
>>     LEGAL_AGE_US = 21
>>     return LEGAL_AGE
>>
>>It doesn’t like LEGAL_AGE_US being all caps if declared in a function.
>
>Yes, I suffered this one too.
>
>The rationale comes from PEP-008 (Constants):
>
>Constants are usually defined on a module level and written in all
>capital letters with underscores separating words.

Yeah. The above looks like a method. I'd probably have something like:

class C:

LEGAL_AGE_US = 21

def is_adult(self) -> bool:
return self.age >= self.LEGAL_AGE_US

Variables used (self). Constant a class attribute.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Personally, I don't particularly like the way you have to put multiline
strings on the far left (rather than aligned with the rest of the scope)
to avoid getting spaces at the beginning of each line. I find it makes
it more difficult to see where the scope of the class/method/etc.
actually ends, especially if there are multiple such strings. It's not
too bad for strings defined at the module level (outer scope) though,
and of course for docstrings the extra spaces at the beginning of each
line don't matter.

However, rather than using "+" to join strings as in your examples
(which, as you suggest, is probably less efficient), I tend to use
string literal concatenation which I gather is more efficient (treated
as a single string at compile-time rather than joining separate strings
at run-time). See
<https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation>.

For example:
HelpText = ("Left click: Open spam\n"
"Shift + Left click: Cook spam\n"
"Right click: Crack egg\n"
"Shift + Right click: Fry egg\n")

The downside is having to put an explicit "\n" at the end of each line,
but to me that's not as bad as having to align the content to the far left.

Getting a bit more on topic, use of backslashes in strings is a bit
different to backslashes for line continuation anyway. You could almost
think of "\
(newline)" in a multiline string as being like an escape sequence
meaning "don't actually put a newline character in the string here", in
a similar way to "\n" meaning "put a newline character here" and "\t"
meaning "put a tab character here".

Mark.


avi.e.gross@gmail.com wrote:
> Good example, Rob, of how some people make what I consider RELIGIOUS edicts that one can easily violate if one wishes and it makes lots of sense in your example.
>
> Let me extend that. The goal was to store a character string consisting of multiple lines when printed that are all left-aligned. Had you written:
>
> HelpText = """
> Left click: Open spam
> ...
> Shift + Right click: Fry egg
> """
> Then it would begin with an extra carriage return you did not want. Your example also ends with a carriage return because you closed the quotes on another line, so a \ on the last line of text (or moving the quotes to the end of the line) would be a way of avoiding that.
>
> Consider some alternatives I have seen that are in a sense ugly and may involve extra work for the interpreter unless it is byte compiled once.
>
> def someFunc():
> HelpText =
> "Left click: Open spam" + "\n" +
> "Shift + Left click: Cook spam" + "\n" +
> ...
>
> Or the variant of:
> HelpText = "Left click: Open spam\n"
> HelpText += " Shift + Left click: Cook spam\n"
> ...
>
> Or perhaps just dumping the multi-line text into a file beforehand and reading that into a string!
>
> def someFunc():
>
> The backslash is not looking like such a bad idea! LOL!
>
> -----Original Message-----
> From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Rob Cliffe via Python-list
> Sent: Wednesday, February 22, 2023 2:08 PM
> To: python-list@python.org
> Subject: Re: Line continuation and comments
>
>
>
> On 22/02/2023 15:23, Paul Bryan wrote:
>> Adding to this, there should be no reason now in recent versions of
>> Python to ever use line continuation. Black goes so far as to state
>> "backslashes are bad and should never be used":
>>
>> https://black.readthedocs.io/en/stable/the_black_code_style/future_sty
>> le.html#using-backslashes-for-with-statements
>
> def someFunc():
> HelpText = """\
> Left click: Open spam
> Shift + Left click: Cook spam
> Right click: Crack egg
> Shift + Right click: Fry egg
> """
>
> The initial backslash aligns the first line with the others (in a fixed font of course).
> Best wishes
> Rob Cliffe
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Mark Bourne schreef op 24/02/2023 om 22:04:
> Personally, I don't particularly like the way you have to put multiline
> strings on the far left (rather than aligned with the rest of the scope)
> to avoid getting spaces at the beginning of each line. I find it makes
> it more difficult to see where the scope of the class/method/etc.
> actually ends, especially if there are multiple such strings. It's not
> too bad for strings defined at the module level (outer scope) though,
> and of course for docstrings the extra spaces at the beginning of each
> line don't matter.
A way around this is using textwrap.dedent()
(https://docs.python.org/3.10/library/textwrap.html?highlight=dedent#textwrap.dedent).
Example from the documentation:

    def test():
        # end first line with \ to avoid the empty line!
        s = '''\
        hello
          world
        '''
        print(repr(s))          # prints '    hello\n world\n    '
        print(repr(dedent(s)))  # prints 'hello\n  world\n'


--
"Met een spitsvondig citaat bewijs je niets."
-- Voltaire

--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
On 25/02/2023 10.04, Mark Bourne wrote:
> Personally, I don't particularly like the way you have to put multiline
> strings on the far left (rather than aligned with the rest of the scope)
> to avoid getting spaces at the beginning of each line.  I find it makes
> it more difficult to see where the scope of the class/method/etc.
> actually ends, especially if there are multiple such strings.  It's not
> too bad for strings defined at the module level (outer scope) though,
> and of course for docstrings the extra spaces at the beginning of each
> line don't matter.
>
> However, rather than using "+" to join strings as in your examples
> (which, as you suggest, is probably less efficient), I tend to use
> string literal concatenation which I gather is more efficient (treated
> as a single string at compile-time rather than joining separate strings
> at run-time).  See
> <https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation>.
>
> For example:
>       HelpText = ("Left click:             Open spam\n"
>                   "Shift + Left click:     Cook spam\n"
>                   "Right click:            Crack egg\n"
>                   "Shift + Right click:    Fry egg\n")
>
> The downside is having to put an explicit "\n" at the end of each line,
> but to me that's not as bad as having to align the content to the far left.

S\Possible solution to that:

HelpText = "\n".join( [."Left click: Open spam",
... "Shift + Left click: Cook spam",
... "Right click: Crack egg",
... "Shift + Right click: Fry egg"
... ]
... )

To PEP-008 Police:
Apologies for formatting - was working from original example

In this manner, the sub-strings may be placed wherever you see fit, and
those pesky line-endings no-longer contribute to visual clutter (but
maybe the brackets do...)

Another philosophy is to move awkward strings, such as the examples in
this thread, 'out' of the mainline code and into a config-file (of sorts).

The PEP-008 Police are more likely to ignore transgressions in a
'data-file' during code-review. So, you can format the code in whatever
fashion you like...


Text for GUIs, report print-outs, etc, tends to be at the (tender) mercy
of (opinionated) users. By putting such into a separate file, such
changes can be made without (as much) risk of 'breaking' the code
itself. Ultimately, if you ever have to expand the application to
multi-tenancy, such will become necessary.

Using a separate file, you can consider if should write such as Python
(import module) or use something else like JSON, YAML, ...
(and may God bless all who sail in her...).

YMMV!


> Getting a bit more on topic, use of backslashes in strings is a bit
> different to backslashes for line continuation anyway.  You could almost
> think of "\
> (newline)" in a multiline string as being like an escape sequence
> meaning "don't actually put a newline character in the string here", in
> a similar way to "\n" meaning "put a newline character here" and "\t"
> meaning "put a tab character here".

Book title: "Don't Make Me Think"
(thoroughly recommended. Author: Steve Krug)

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Paul Bryan wrote:
> Adding to this, there should be no reason now in recent versions of
> Python to ever use line continuation. Black goes so far as to state
> "backslashes are bad and should never be used":
>
> https://black.readthedocs.io/en/stable/the_black_code_style/
future_style.html#using-backslashes-for-with-statements

Then I wonder how Mr. Black would go about these long "dot chaining"
expressions that packages like pandas and sqlalchemy require.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Edmondo Giovannozzi wrote:
> 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

I like that. Never thought of it.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Line continuation and comments [ In reply to ]
Robert Latest wrote:
> Paul Bryan wrote:
>> Adding to this, there should be no reason now in recent versions of
>> Python to ever use line continuation. Black goes so far as to state
>> "backslashes are bad and should never be used":
>>
>> https://black.readthedocs.io/en/stable/the_black_code_style/
> future_style.html#using-backslashes-for-with-statements
>
> Then I wonder how Mr. Black would go about these long "dot chaining"
> expressions that packages like pandas and sqlalchemy require.

Just found out that parentheses work there, too.
--
https://mail.python.org/mailman/listinfo/python-list