PEP8 breaking long string in assert
本问题已经有最佳答案,请猛点这里访问。
我有这行代码:
1 | assert 0 <= j <= self.n,"First edge needs to be between 0 and {}".format(self.n) |
我想让Pep8开心,但我不知道如何打破这条线。我试图在逗号后中断,但得到了无效的语法。我尝试过用附加的""来断开字符串,比如如何断开长字符串以符合PEP8?.pep8很高兴,但断言只产生了消息的前半部分。
断开长断言字符串的正确方法是什么?
使用父母:
1 2 | assert 0 <= j <= self.n, ("First edge needs to be" "between 0 and {}".format(self.n)) |
或:
1 2 | assert 0 <= j <= self.n, ("First edge needs to be between 0 and {}" .format(self.n)) |
或者使用
1 2 | assert 0 <= j <= self.n,"First edge needs to be between 0 and {}".format( self.n) |
考虑到在使用
1 2 | assert 0 <= j <= self.n, ('First edge needs to be between ' '0 and {}'.format(self.n)) |
或者在python 3.6+中使用f字符串:
1 2 | assert 0 <= j <= self.n, ('First edge needs to be between ' f'0 and {self.n}') |
如果您不关心优化(例如编写测试),那么将行分成两个语句也是一个选项:
1 2 | message = 'First edge needs to be between 0 and {}'.format(self.n) assert 0 <= j <= self.n, message |
您可以强制断开到这样的新行:
1 2 | assert 0 <= j <= self.n,\ "print stuff" |
如果括号和括号不是自动执行的,这总是使行继续。你可以把下一行缩进到最可读的地方,就像我上面所做的。