如何写非常长的符合PEP8和防止E501的字符串

正如PEP8所建议的那样,在python程序中保持低于80列的规则,对于长字符串,我怎么能遵守这个规则呢?

s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."

我该如何把它扩展到下面一行呢?

s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
113154 次浏览

反斜杠:

s = "this is my really, really, really, really, really, really" +  \
"really long string that I'd like to shorten."

或者用括号括起来:

s = ("this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten.")

使用\可以将语句扩展为多行:

s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."

应该工作。

您丢失了一个空格,您可能需要一个行延续字符,即。\

s = "this is my really, really, really, really, really, really" +  \
" really long string that I'd like to shorten."

甚至:

s = "this is my really, really, really, really, really, really"  \
" really long string that I'd like to shorten."

parns也可以代替行续符,但可能会有人认为您打算使用元组,而只是忘记了逗号。举个例子:

s = ("this is my really, really, really, really, really, really"
" really long string that I'd like to shorten.")

对比:

s = ("this is my really, really, really, really, really, really",
" really long string that I'd like to shorten.")

使用Python的动态类型,代码可以以任何一种方式运行,但会产生不正确的结果。

我觉得你问题中最重要的一个词是“suggest”。

编码标准是很有趣的东西。通常他们提供的指导在编写时有很好的基础(例如,大多数终端无法在一行上显示> 80个字符),但随着时间的推移,它们在功能上变得过时了,但仍然被严格遵守。我猜您在这里需要做的是权衡“破坏”特定建议与代码的可读性和可维护性之间的相对优点。

抱歉,这并不能直接回答你的问题。

隐式连接可能是最干净的解决方案:

s = "this is my really, really, really, really, really, really," \
" really long string that I'd like to shorten."

编辑经过反思,我同意Todd的建议,使用括号而不是行续,因为他给出的所有原因更好。我唯一的犹豫是,用括号括起来的字符串和元组比较容易混淆。

因为相邻的字符串常量是自动连接的,你可以这样编码:

s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")

注意没有加号,我在示例的格式后面添加了额外的逗号和空格。

就我个人而言,我不喜欢反斜杠,我记得在某个地方读到过,它的使用实际上是被反对的,而支持这种更明确的形式。记住“明胜于暗”;

我认为反斜杠不太清楚,也不太有用,因为这实际上是转义换行符。如果需要的话,不能在它后面加上行结束注释。可以通过串接字符串常量来实现:

s = ("this is my really, really, really, really, really, really, " # comments ok
"really long string that I'd like to shorten.")

我使用谷歌搜索“python行长度”;它返回PEP8链接作为第一个结果,但也链接到另一个好的StackOverflow关于这个主题的帖子:

另一个不错的搜索短语是“python line continuation”。

我倾向于使用几个这里没有提到的方法来指定大字符串,但这些方法适用于非常特定的场景。YMMV……

  • 多行文本,通常带有格式化的标记(不完全是你想要的,但仍然有用):

    error_message = '''
    I generally like to see how my helpful, sometimes multi-line error
    messages will look against the left border.
    '''.strip()
    
  • Grow the variable piece-by-piece through whatever string interpolation method you prefer:

    var = 'This is the start of a very,'
    var = f'{var} very long string which could'
    var = f'{var} contain a ridiculous number'
    var = f'{var} of words.'
    
  • Read it from a file. PEP-8 doesn't limit the length of strings in a file; just the lines of your code. :)

  • Use brute-force or your editor to split the string into managaeble lines using newlines, and then remove all newlines. (Similar to the first technique I listed):

    foo = '''
    agreatbigstringthatyoudonotwanttohaveanyne
    wlinesinbutforsomereasonyouneedtospecifyit
    verbatimintheactualcodejustlikethis
    '''.replace('\n', '')
    

我以前用过textwrap.dedent。这有点麻烦,所以我现在更喜欢行延续,但如果你真的想要块缩进,我认为这很好。

示例代码(其中trim是去掉带有切片的第一个'\n'):

import textwrap as tw
x = """\
This is a yet another test.
This is only a test"""
print(tw.dedent(x))

解释:

Dedent根据新行前第一行文本中的空白计算缩进。如果你想调整它,你可以使用re模块轻松地重新实现它。

这种方法有局限性,很长的行可能仍然比你想要的长,在这种情况下,其他方法连接字符串更适合。

这些都是很好的答案,但我找不到一个编辑器插件,可以帮助我编辑“隐式连接”的字符串,所以我写了一个包,让我更容易。

在pip(安装段落)上,如果有人想查看这个旧线程的话。以html的方式格式化多行字符串(压缩空格,一个新段落有两个换行符,不用担心行间空格)。

from paragraphs import par




class SuddenDeathError(Exception):
def __init__(self, cause: str) -> None:
self.cause = cause


def __str__(self):
return par(
f""" Y - e - e - e - es, Lord love you! Why should she die of
{self.cause}? She come through diphtheria right enough the year
before. I saw her with my own eyes. Fairly blue with it, she
was. They all thought she was dead; but my father he kept ladling
gin down her throat till she came to so sudden that she bit the bowl
off the spoon.


What call would a woman with that strength in her have to die of
{self.cause}? What become of her new straw hat that should have
come to me? Somebody pinched it; and what I say is, them as pinched
it done her in."""
)




raise SuddenDeathError("influenza")


变得……

__main__.SuddenDeathError: Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through diphtheria right enough the year before. I saw her with my own eyes. Fairly blue with it, she was. They all thought she was dead; but my father he kept ladling gin down her throat till she came to so sudden that she bit the bowl off the spoon.


What call would a woman with that strength in her have to die of influenza? What become of her new straw hat that should have come to me? Somebody pinched it; and what I say is, them as pinched it done her in.

一切都很容易与(Vim)对齐“gq”

可用的选项:

  • 反斜杠: "foo" \ "bar"
  • 加号后面跟着反斜杠: "foo" + \ "bar"
  • <李> 括号:
    • ("foo" "bar")
    • 括号加号: ("foo" + "bar")
    • PEP8, E502:括号之间的反斜杠是多余的

避免

避免括号中有逗号:("foo", "bar")定义了一个元组。


>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" +
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>>

如果你必须插入一个长字符串文字,并希望flake8关闭,你可以使用它的关闭指令。例如,在一个测试例程中,我定义了一些假的CSV输入。我发现将它分割成更多行会非常混乱,所以我决定添加# noqa: E501,如下所示:

csv_test_content = """"STATION","DATE","SOURCE","LATITUDE","LONGITUDE","ELEVATION","NAME","REPORT_TYPE","CALL_SIGN","QUALITY_CONTROL","WND","CIG","VIS","TMP","DEW","SLP","AA1","AA2","AY1","AY2","GF1","MW1","REM"
"94733099999","2019-01-03T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","050,1,N,0010,1","22000,1,9,N","025000,1,9,9","+0260,1","+0210,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1","01,99,1,99,9,99,9,99999,9,99,9,99,9","01,1","SYN05294733 11/75 10502 10260 20210 60004 70100 333 70000="
"94733099999","2019-01-04T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","090,1,N,0021,1","22000,1,9,N","025000,1,9,9","+0378,1","+0172,1","99999,9","06,0000,9,1",,"0,1,02,1","0,1,02,1","03,99,1,99,9,99,9,99999,9,99,9,99,9","03,1","SYN04294733 11/75 30904 10378 20172 60001 70300="
"94733099999","2019-01-04T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","290,1,N,0057,1","99999,9,9,N","020000,1,9,9","+0339,1","+0201,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1",,"02,1","SYN05294733 11970 02911 10339 20201 60004 70200 333 70000="
"94733099999","2019-01-05T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","200,1,N,0026,1","99999,9,9,N","000100,1,9,9","+0209,1","+0193,1","99999,9","24,0004,3,1",,"1,1,02,1","1,1,02,1","08,99,1,99,9,99,9,99999,9,99,9,99,9","51,1","SYN05294733 11/01 82005 10209 20193 69944 75111 333 70004="
"94733099999","2019-01-08T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","070,1,N,0026,1","22000,1,9,N","025000,1,9,9","+0344,1","+0213,1","99999,9","06,0000,9,1",,"2,1,02,1","2,1,02,1","04,99,1,99,9,99,9,99999,9,99,9,99,9","02,1","SYN04294733 11/75 40705 10344 20213 60001 70222="
"""  # noqa: E501

使用黑色的 [https://github.com/psf/black]我像这样格式化它。

   help=f"""filters, lista de filtros para cargar las base de conocimiento.
Pueden mandarse solo algunos filtros ya que no son obligatorios,
por ejemplo, si no se manda sts, se cargarán todos las bases de todos los estados.""",
message = f"Variable : child({type(child)}) -> is not of"\
" type Node."

这个语法适合我。注意第二个语句的缩进,它应该缩进正确。