Вопрос-Ответ

How can I do a line break (line continuation) in Python (split up a long line of source code)?

Как я могу сделать разрыв строки (продолжение строки) в Python (разделить длинную строку исходного кода)?

Дано:

e = 'a' + 'b' + 'c' + 'd'

Как мне записать вышесказанное в две строки?

e = 'a' + 'b' +
'c' + 'd'
Переведено автоматически
Ответ 1

Что это за строка? Вы можете просто иметь аргументы в следующей строке без каких-либо проблем:

a = dostuff(blahblah3, blahblah2, blahblah3, blahblah4, blahblah5, 
blahblah6, blahblah7)

В противном случае вы можете сделать что-то вроде этого:

if (a == True and
b == False):

или с явным переносом строки:

if a == True and \
b == False:

Проверьте руководство по стилю для получения дополнительной информации.

Используя круглые скобки, ваш пример может быть записан в нескольких строках:

a = ('1' + '2' + '3' +
'4' + '5')

Тот же эффект можно получить, используя явный перенос строки:

a = '1' + '2' + '3' + \
'4' + '5'

Обратите внимание, что в руководстве по стилю говорится, что предпочтительнее использовать неявное продолжение в круглых скобках, но в данном конкретном случае просто добавлять круглые скобки вокруг вашего выражения, вероятно, неправильный путь.

Ответ 2

Из PEP 8 -- Руководство по стилю для кода Python:


Предпочтительный способ переноса длинных строк - использовать подразумеваемое продолжение строки в круглых скобках Python. Длинные строки можно разбить на несколько строк, заключив выражения в круглые скобки. Их следует использовать предпочтительнее, чем обратную косую черту для продолжения строки.



Обратная косая черта все еще может иногда быть уместной. Например, длинные множественные операторы with- не могут использовать неявное продолжение, поэтому обратная косая черта приемлема:



with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())

Другой подобный случай связан с операторами assert .



Убедитесь, что в продолжении строки сделан соответствующий отступ. Предпочтительное место для разрыва вокруг двоичного оператора - после оператора, а не перед ним. Несколько примеров:



class Rectangle(Blob):

def __init__(self, width, height,
color='black', emphasis=None, highlight=0
):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)file_2.write(file_1.read())

PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.

Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.

From PEP8: Should a line break before or after a binary operator?:


Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].



Following the tradition from mathematics usually results in more readable code:



# Yes: easy to match operators with operands

income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.


[3]: Donald Knuth's The TeXBook, pages 195 and 196

Ответ 3

The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.

Ответ 4

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))

or

b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
python