样式,格式化切片运算符 [英] style, formatting the slice operator
问题描述
PEP 8 没有提及切片运算符。从我的理解,不像其他运算符,它不应该被空格包围
spam [3:5]#OK
spam [3:5]#NOT OK
使用复杂表达式时,一个被认为是更好的风格
1.垃圾邮件[ham(66)// 3:44 + eggs 2. spam [ham(66)// 3:44 + eggs()]
3. spam [ham(66)// 3:44 + eggs()]
4.别的什么?正如你已经提到的,PEP8没有明确提到该格式的slice运算符,因此,但是spam [3:5]
肯定更常见,IMHO更易读。
如果 pep8 checker 是什么,
:
之前的空格将被标记 p>
[me @ home] $ pep8<(echospam [3:44])#无警告
[ me @ home] $ pep8<(echospam [3:44])
/ dev / fd / 63:1:7:E203之前的空白':'
...但这只是因为它假定
:
并且在操作员之前没有空间。spam [3:44]
因为这个原因,但似乎不对。
计数,我坚持
spam [3:44]
。
嵌套算术运算有点棘手。在您的3个示例中,只有第2个通过PEP8验证:
[me @ home] $ pep8< [ham(66)// 3:44 + eggs()])
/ dev / fd / 63:1:13:E225缺少操作符周围的空格
[ $ pep8<(echospam [ham(66)// 3:44 + eggs()])#OK
[me @ home] $ pep8< (66)// 3:44 + eggs()])
/ dev / fd / 63:1:18:E203之前的空白':'
但是,我发现上面所有的一切都很难一目了然。
符合PEP8,我亲自去:
spam [(ham(66)/ / 3):( 44 + eggs())]
>
s_from = ham(66)// 3
s_to = 44 + eggs $ b spam [s_from:s_to]
PEP 8 doesn't mention the slice operator. From my understanding, unlike other operators, it should not be surrounded with whitespace
spam[3:5] # OK spam[3 : 5] # NOT OK
Does this hold when using complex expressions, that is, which one is considered better style
1. spam[ham(66)//3:44+eggs()] 2. spam[ham(66) // 3: 44 + eggs()] 3. spam[ham(66) // 3 : 44 + eggs()] 4. something else?
解决方案As you already mentioned, PEP8 doesn't explicitly mention the slice operator in that format, but
spam[3:5]
is definitely more common and IMHO more readable.If pep8 checker is anything to go by, the space before
:
will be flagged up[me@home]$ pep8 <(echo "spam[3:44]") # no warnings [me@home]$ pep8 <(echo "spam[3 : 44]") /dev/fd/63:1:7: E203 whitespace before ':'
... but that's only because of it assumes
:
to be the operator for defining a literal dict and no space is expected before the operator.spam[3: 44]
passes for that reason, but that just doesn't seem right.On that count, I'd stick to
spam[3:44]
.
Nested arithmetic operations are a little trickier. Of your 3 examples, only the 2nd one passes PEP8 validation:
[me@home]$ pep8 <(echo "spam[ham(66)//3:44+eggs()]") /dev/fd/63:1:13: E225 missing whitespace around operator [me@home]$ pep8 <(echo "spam[ham(66) // 3:44 + eggs()]") # OK [me@home]$ pep8 <(echo "spam[ham(66) // 3 : 44 + eggs()]") /dev/fd/63:1:18: E203 whitespace before ':'
However, I find all of the above difficult to parse by eye at first glance.
For readability and compliance with PEP8, I'd personally go for:
spam[(ham(66) // 3):(44 + eggs())]
Or for more complication operations:
s_from = ham(66) // 3 s_to = 44 + eggs() spam[s_from:s_to]
这篇关于样式,格式化切片运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!