I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
我有一长串的代码想要在多行中分解。我使用什么,语法是什么?
For example, adding a bunch of strings,
例如,添加一串字符串,
e = 'a' + 'b' + 'c' + 'd'
and have it in two lines like this:
有两条这样的线:
e = 'a' + 'b' +
'c' + 'd'
6 个解决方案
#1
867
What is the line? You can just have arguments on the next line without any problems:
这条线是什么?你可以在没有任何问题的情况下对下一行进行论证:
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
Otherwise you can do something like this:
否则你可以这样做:
if a == True and \
b == False
Check the style guide for more information.
查看风格指南以获取更多信息。
From your example line:
从你的例子:
a = '1' + '2' + '3' + \
'4' + '5'
Or:
或者:
a = ('1' + '2' + '3' +
'4' + '5')
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.
注意,样式指南说使用隐式的延续是首选的,但是在这个特殊的情况下,在表达式周围添加圆括号可能是错误的方法。
#2
166
From Style Guide for Python Code:
从Python代码的风格指南:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
用Python的隐含行继续在圆括号、方括号和大括号中,是包装长行的首选方法。通过在圆括号中封装表达式,可以在多行中划分长行。这些应该用于优先使用反斜杠进行行延续。
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
反斜杠有时仍然是合适的。例如,long,多个with-statement不能使用隐式延续,所以反斜杠是可以接受的:
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())
Another such case is with assert statements.
另一个这样的例子是断言语句。
Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:
确保适当地缩进继续行。一个二元运算符的首选位置是在运算符之后,而不是在它之前。一些例子:
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)
EDIT: PEP8 now recommends the opposite convention (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.
编辑:PEP8现在建议数学家和他们的出版商使用相反的惯例(打破二进制操作)来提高可读性。
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.
Donald Knuth在二进制操作符前的破坏风格将操作符垂直对齐,从而在确定添加和减去哪些项时减少了眼睛的工作量。
From PEP8: Should a line break before or after a binary operator?:
从PEP8:在二元运算符之前或之后的换行?
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].
Donald Knuth在他的计算机和排版系列中解释了传统的规则:“尽管在一段内的公式总是在二进制运算和关系之后中断,显示的公式总是在二进制运算之前中断”[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.
在Python代码中,只要该约定在本地是一致的,就允许在二进制操作符之前或之后中断。对于新代码Knuth的风格建议。
[3]: Donald Knuth's The TeXBook, pages 195 and 196
[3]:Donald Knuth的《德克萨斯书》,第195页和第196页。
#3
58
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.
更多的内容参见Python的习语和反习语(用于Python 2或Python 3)。
#4
20
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
您可以在圆括号和大括号之间分隔线。此外,您可以将反斜杠字符添加到一个行中,以显式地将其断开:
x = (tuples_first_value,
second_value)
y = 1 + \
2
#5
18
Put a \
at the end of your line or enclose the statement in parens ( .. )
. From IBM:
在你的电话线的末端放上一个\,或者把声明放在parens(..)中。来自IBM的:
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
or
或
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
#6
16
From the horse's mouth: Explicit line joining
从马的嘴:明确的线连接。
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:两个或两个以上的物理线路可能会加入到逻辑线路使用反斜杠字符(\)如下:当一个物理行以一个反斜杠,不是字符串或评论的一部分,它是与下面形成一个逻辑行,删除反斜杠和下面的行尾字符。例如:
if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
以反斜杠结尾的行不能进行注释。反斜杠不会继续注释。一个反斜杠不会继续一个令牌,除非是字符串字面值(即:,不能用反斜杠在物理行上分隔符号,而不是字符串。反斜杠在字符串字面上的其他地方是非法的。
#1
867
What is the line? You can just have arguments on the next line without any problems:
这条线是什么?你可以在没有任何问题的情况下对下一行进行论证:
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
Otherwise you can do something like this:
否则你可以这样做:
if a == True and \
b == False
Check the style guide for more information.
查看风格指南以获取更多信息。
From your example line:
从你的例子:
a = '1' + '2' + '3' + \
'4' + '5'
Or:
或者:
a = ('1' + '2' + '3' +
'4' + '5')
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.
注意,样式指南说使用隐式的延续是首选的,但是在这个特殊的情况下,在表达式周围添加圆括号可能是错误的方法。
#2
166
From Style Guide for Python Code:
从Python代码的风格指南:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
用Python的隐含行继续在圆括号、方括号和大括号中,是包装长行的首选方法。通过在圆括号中封装表达式,可以在多行中划分长行。这些应该用于优先使用反斜杠进行行延续。
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
反斜杠有时仍然是合适的。例如,long,多个with-statement不能使用隐式延续,所以反斜杠是可以接受的:
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())
Another such case is with assert statements.
另一个这样的例子是断言语句。
Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:
确保适当地缩进继续行。一个二元运算符的首选位置是在运算符之后,而不是在它之前。一些例子:
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)
EDIT: PEP8 now recommends the opposite convention (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.
编辑:PEP8现在建议数学家和他们的出版商使用相反的惯例(打破二进制操作)来提高可读性。
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.
Donald Knuth在二进制操作符前的破坏风格将操作符垂直对齐,从而在确定添加和减去哪些项时减少了眼睛的工作量。
From PEP8: Should a line break before or after a binary operator?:
从PEP8:在二元运算符之前或之后的换行?
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].
Donald Knuth在他的计算机和排版系列中解释了传统的规则:“尽管在一段内的公式总是在二进制运算和关系之后中断,显示的公式总是在二进制运算之前中断”[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.
在Python代码中,只要该约定在本地是一致的,就允许在二进制操作符之前或之后中断。对于新代码Knuth的风格建议。
[3]: Donald Knuth's The TeXBook, pages 195 and 196
[3]:Donald Knuth的《德克萨斯书》,第195页和第196页。
#3
58
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.
更多的内容参见Python的习语和反习语(用于Python 2或Python 3)。
#4
20
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
您可以在圆括号和大括号之间分隔线。此外,您可以将反斜杠字符添加到一个行中,以显式地将其断开:
x = (tuples_first_value,
second_value)
y = 1 + \
2
#5
18
Put a \
at the end of your line or enclose the statement in parens ( .. )
. From IBM:
在你的电话线的末端放上一个\,或者把声明放在parens(..)中。来自IBM的:
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
or
或
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
#6
16
From the horse's mouth: Explicit line joining
从马的嘴:明确的线连接。
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:两个或两个以上的物理线路可能会加入到逻辑线路使用反斜杠字符(\)如下:当一个物理行以一个反斜杠,不是字符串或评论的一部分,它是与下面形成一个逻辑行,删除反斜杠和下面的行尾字符。例如:
if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
以反斜杠结尾的行不能进行注释。反斜杠不会继续注释。一个反斜杠不会继续一个令牌,除非是字符串字面值(即:,不能用反斜杠在物理行上分隔符号,而不是字符串。反斜杠在字符串字面上的其他地方是非法的。