在 Python 中链接方法时正确的换行样式
我有一些这样的代码。休息时间应该在经期之前还是之后?
# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)
# this way
my_var = somethinglikethis.where(we=do_things) \
.where(we=domore) \
.where(we=everdomore)
# or this way
my_var = somethinglikethis.where(we=do_things). \
where(we=domore). \
where(we=everdomore)
I have some code like this. Should the break occur before the periods or after?
# before
my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)
# this way
my_var = somethinglikethis.where(we=do_things) \
.where(we=domore) \
.where(we=everdomore)
# or this way
my_var = somethinglikethis.where(we=do_things). \
where(we=domore). \
where(we=everdomore)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PEP 8 建议使用括号,这样您就不需要
\
,并温和地建议在二元运算符之前而不是之后断开。因此,格式化代码的首选方式如下:两个相关段落是来自 最大行长度 部分:
...以及整个 应该在二元运算符之前还是之后换行? 部分:
请注意,如上面的引用所示,PEP 8 曾经给出了关于在哪里突破运算符的相反建议,如下引用以供后代使用:
PEP 8 recommends using parenthesis so that you don't need
\
, and gently suggests breaking before binary operators instead of after them. Thus, the preferred way of formatting you code is like this:The two relevant passages are this one from the Maximum Line Length section:
... and the entire Should a line break before or after a binary operator? section:
Note that, as indicated in the quote above, PEP 8 used to give the opposite advice about where to break around an operator, quoted below for posterity:
FWIW, autopep8 (带有
--aggressive
标志)产生了这个来自你的原始代码:但我同意——巴斯蒂安的解决方案更优雅。
FWIW, autopep8 (with an
--aggressive
flag) produced this from your original code:But I agree -- Bastien's solution is more elegant.
做有效的事情。
另外,请查看有关 Python 中缩进神话的白皮书。可以找到这里。
它开始于:
我希望这有帮助。
Do what works.
Also, check out this whitepaper on the myths of indentation in Python. That can be found here.
It starts out with:
I hope that helps.