pr0*_*n8r 4 python code-formatting conventions
我知道行宽的标准Python约定是79个字符.我知道可以通过多种方式继续行,例如自动字符串连接,括号和反斜杠.似乎没有明确定义的是如何格式化溢出文本.我是否一直将它推回到第1组?到原始线开始的col?到括号的开头(如果适用)?例如,说我有这样的事情:
self.someLongAttributeName = {'someLongKeyName':'someLongValueName',
'anotherLongKeyName':'anotherLongValueName'}
Run Code Online (Sandbox Code Playgroud)
假设我上面使用的格式符合79个字符的限制,第二行的缩进是否正确?
现在假设上面显示的第一行> 79个字符.在这种情况下应该怎么看?
注意:我知道很多人不同意79个字符的约定.虽然我尊重问题的每一方都有很多利弊,但这次辩论与我的问题无关.我问的是如何遵循惯例,而不是我是否应该遵守,所以请不要在回复中支持放弃它的好处.谢谢.=)
小智 11
假设我上面使用的格式符合79个字符的限制,第二行的缩进是否正确?
是的,这就是PEP 8在示例中显示的方式:
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)
Run Code Online (Sandbox Code Playgroud)
但是当开括号/括号已经接近第79列时,我通常只是利用它:
Two good reasons to break a particular rule:
(1) When applying the rule would make the code less readable, even for
someone who is used to reading code that follows the rules.
[...]
Run Code Online (Sandbox Code Playgroud)
并做一些类似的事情
self.some_long_attribute_name = {
'someLongKeyName': 'someLongValueName',
'anotherLongKeyName': 'anotherLongValueName'
}
Run Code Online (Sandbox Code Playgroud)
要么
long_object_name.do_something_with_long_name(
long_expression_returning_is_first_arg,
long_expression_returning_is_second_arg
)
Run Code Online (Sandbox Code Playgroud)
http://www.python.org/dev/peps/pep-0008/
请参阅Maximum Line Length
将所有行限制为最多79个字符.
周围仍有许多设备仅限于80个字符行; 此外,将窗口限制为80个字符可以并排放置多个窗口.这些设备的默认包装破坏了代码的可视化结构,使其更难理解.因此,请将所有行限制为最多79个字符.对于流动长文本块(文档字符串或注释),建议将长度限制为72个字符.
包装长行的首选方法是在括号,括号和括号内使用Pythons隐含的行连续.如有必要,您可以在表达式周围添加一对额外的括号,但有时使用反斜杠看起来更好.确保适当缩进续行.打破二元运算符的首选位置是运算符 之后,而不是它之前.一些例子:
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)
Run Code Online (Sandbox Code Playgroud)