Put comments inside a multi-line literal list

I am making an optimization problem and writing down a giant list. I would like to insert comments inside the list as below

my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1 -1.0, -1.0, -1.0,\ #comment2 0.0, 0.0, 0.0] 

but when I do this, Python gives an error. How can I comment in the indicated places? I tried to define each line as a new list and use + to add, but this does not work either. As below

 my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0]+\ #comment1 [-1.0, -1.0, -1.0]+\ #comment2 [0.0, 0.0, 0.0] 

How can I comment in the places shown without Python error?

+6
source share
1 answer

You just need to remove the backslash characters:

 my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1 -1.0, -1.0, -1.0, # comment2 0.0, 0.0, 0.0] 

Below is a demo:

 >>> my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1 ... -1.0, -1.0, -1.0, # comment2 ... 0.0, 0.0, 0.0] >>> my_rhs [1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0] >>> 

The \ character tells Python that the next line is part of the current line. So he interprets this:

 my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1 -1.0, -1.0, -1.0,\ #comment2 0.0, 0.0, 0.0] 

How equivalent to this:

 my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, #comment1 -1.0, -1.0, -1.0, #comment2 0.0, 0.0, 0.0] 

It should be noted that PEP 8 , the official style guide for Python code, contains a section on wrapping long lines:

The preferred way to wrap long lines is to use Python's implied line continuation in parentheses, brackets, and curly braces. Long lines can be split into multiple lines by wrapping expressions in parentheses. They should be used instead of using a backslash to continue the line.

This excerpt from Explicit String Join also matters:

A line ending with a backslash cannot contain a comment. The backslash does not continue the comment. The backslash does not continue the token, except for string literals (i.e. tokens other than string literals cannot be separated by physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

+9
source

Source: https://habr.com/ru/post/972420/


All Articles