My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of when the line is going to flow over. These let me plan logical lines that will fit on multiple physical lines.
As for how to actually fit them, there are several mechanisms. You can end the line with a \ , but this is error prone.
# works
print 4 + \
2
# doesn't work
print 4 + \
2
The difference? The difference is invisible-- there was a whitespace character after the backslash in the second case. Oops!
What should be done instead? Well, surround it in parentheses.
print (4 +
2)
No \ needed. This actually works universally, you will never ever need \ . Even for attribute access boundaries!
print (foo
.bar())
For strings, you can add them explicitly, or implicitly using C-style joining.
# all of these do exactly the same thing
print ("123"
"456")
print ("123" +
"456")
print "123456"
Finally, anything that will be in any form of bracket ((), []. {}), not just parentheses in particular, can have a line break placed anywhere. So, for example, you can use a list literal over multiple lines just fine, so long as elements are separated by a comma.
All this and more can be found in the official documentation for Python. Also, a quick note, PEP-8 specifies 79 characters as the limit, not 80-- if you have 80 characters, you are already over it.
If the code exceeding 80 chars is a function call (or definition), break the argument line. Python will recognise the parenthesis, and sees that as one line.
function(arg, arg, arg, arg,
arg, arg, arg...)
If the code exceeding 80 chars is a line of code that isn't naturally breakable, you can use the backslash \ to "escape" the newline.
this_is_a_long_string = ("lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj "
"rest of the string: no string addition is necessary!"
" You can do it many times!")
Strings can be automatically concatenated, which is very convenient:
this_is_a_long_string = ("lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj "
"rest of the string: no string addition is necessary!"
" You can do it many times!")
Note that this is efficient: this does not result in string concatenations calculated when the code is run: instead, this is directly considered as a single long string literal, so it is efficient.
A little caveat related to Devin's answer: the "parenthesis" syntax actually does not "work universally". For instance, d[42] = "H22G" cannot be written as
(d
[42] = "H2G2")
Parentheses can be used around "calculated" expression (which does not include an assignment (=) like above).
Another example was the following code, which used to generate a syntax error (at some point before Python 3.9):
with (open("..... very long file name .....")
as input_file):
In fact, parentheses cannot be put around any statement, more generally (only expressions).
In these cases, one can either use the "" syntax, or, better (since "" is to be avoided if possible), split the code over multiple statements.
So, if using parentheses () is possible, avoid backslashes. If you have a a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states() do something like:
发布评论
评论(4)
我当前的编辑器 (Kate) 已配置为每当行长度达到或超过 80 个字符时在单词边界上引入换行符。这立即表明我已经超越了界限。此外,还有一条红线标记了 80 个字符的位置,提前警告我该线何时会溢出。这些让我可以规划适合多条物理线路的逻辑线路。
至于如何实际适应它们,有几种机制。您可以用 \ 结束该行,但这很容易出错。
区别?区别是不可见的——在第二种情况下,反斜杠后面有一个空格字符。哎呀!
应该做什么呢?好吧,把它放在括号里。
不需要 \ 。这实际上是普遍有效的,你永远不需要 \ 。即使对于属性访问边界!
对于字符串,您可以显式添加它们,也可以使用 C 样式连接隐式添加它们。
最后,任何形式的方括号((),[]。{}),而不仅仅是圆括号,都可以在任何地方放置换行符。因此,例如,您可以在多行上使用列表文字,只要元素之间用逗号分隔即可。
所有这些以及更多内容都可以在 Python 的官方文档中找到。另外,请注意, PEP-8 指定 79 个字符作为限制,不是80——如果你有80个字符,你就已经超过了。
My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of when the line is going to flow over. These let me plan logical lines that will fit on multiple physical lines.
As for how to actually fit them, there are several mechanisms. You can end the line with a \ , but this is error prone.
The difference? The difference is invisible-- there was a whitespace character after the backslash in the second case. Oops!
What should be done instead? Well, surround it in parentheses.
No \ needed. This actually works universally, you will never ever need \ . Even for attribute access boundaries!
For strings, you can add them explicitly, or implicitly using C-style joining.
Finally, anything that will be in any form of bracket ((), []. {}), not just parentheses in particular, can have a line break placed anywhere. So, for example, you can use a list literal over multiple lines just fine, so long as elements are separated by a comma.
All this and more can be found in the official documentation for Python. Also, a quick note, PEP-8 specifies 79 characters as the limit, not 80-- if you have 80 characters, you are already over it.
如果超过 80 个字符的代码是函数调用(或定义),请断开参数行。 Python 会识别括号,并将其视为一行。
如果超过 80 个字符的代码是不可自然破坏的代码行,则可以使用反斜杠
\
来“转义”换行符。您还可以使用括号来发挥您的优势。
所有类型的集合括号 {}(字典/集合)、[](列表)、()(元组)都可以毫无问题地跨多行。这允许更好的格式化。
If the code exceeding 80 chars is a function call (or definition), break the argument line. Python will recognise the parenthesis, and sees that as one line.
If the code exceeding 80 chars is a line of code that isn't naturally breakable, you can use the backslash
\
to "escape" the newline.You can also use the parenthesis to your advantage.
All types of set brackets {} (dict/set), [] (list), () (tuples) can be broken across several lines without problems. This allows for nicer formatting.
我想在前面的答案中添加两点:
字符串可以自动连接,这非常方便:
请注意,这很有效:这不会导致代码运行时计算字符串连接:相反,这直接被视为单个长字符串文字,因此效率很高。
与德文的回答相关的一点警告:“括号”语法实际上并不“普遍适用”。例如,d[42] = "H22G" 不能写为
括号可以用在“计算”表达式周围(不包括像上面那样的赋值 (=))。
另一个例子是下面的代码,它曾经生成语法错误(在 Python 3.9 之前的某个时候):
事实上,更一般地说,括号不能放在任何语句周围(仅限表达式)。
在这些情况下,可以使用“”语法,或者更好的方法(因为如果可能的话应避免“”),将代码拆分为多个语句。
I would add two points to the previous answers:
Strings can be automatically concatenated, which is very convenient:
Note that this is efficient: this does not result in string concatenations calculated when the code is run: instead, this is directly considered as a single long string literal, so it is efficient.
A little caveat related to Devin's answer: the "parenthesis" syntax actually does not "work universally". For instance, d[42] = "H22G" cannot be written as
Parentheses can be used around "calculated" expression (which does not include an assignment (=) like above).
Another example was the following code, which used to generate a syntax error (at some point before Python 3.9):
In fact, parentheses cannot be put around any statement, more generally (only expressions).
In these cases, one can either use the "" syntax, or, better (since "" is to be avoided if possible), split the code over multiple statements.
惯用的Python 说:
因此,如果可以使用括号
()
,请避免使用反斜杠。如果您有一个
a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states()
做类似的事情:或者,最好重构你的代码。请。
Idiomatic Python says:
So, if using parentheses
()
is possible, avoid backslashes.If you have a
a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states()
do something like:Or, preferably, refactor your code. Please.