Python 样式,格式化切片操作符

Python 样式,格式化切片操作符,python,coding-style,Python,Coding Style,没有提到切片操作符。根据我的理解,与其他操作符不同,它不应该被空格包围 spam[3:5] # OK spam[3 : 5] # NOT OK 当使用复杂表达式时,也就是说,哪一个被认为是更好的样式时,这是否成立 1. spam[ham(66)//3:44+eggs()] 2. spam[ham(66) // 3: 44 + eggs()] 3. spam[ham(66) // 3 : 44 + eggs()] 4. something else? 1.垃圾邮

没有提到切片操作符。根据我的理解,与其他操作符不同,它不应该被空格包围

spam[3:5]   # OK
spam[3 : 5] # NOT OK
当使用复杂表达式时,也就是说,哪一个被认为是更好的样式时,这是否成立

1. spam[ham(66)//3:44+eggs()] 2. spam[ham(66) // 3: 44 + eggs()] 3. spam[ham(66) // 3 : 44 + eggs()] 4. something else? 1.垃圾邮件[火腿(66)//3:44+鸡蛋() 2.垃圾邮件[火腿(66)//3:44+鸡蛋() 3.垃圾邮件[火腿(66)//3:44+鸡蛋() 4.还有别的吗?
我同意你的第一个例子。对于后者:。可读性很重要。复杂切片表达式语义上最重要的部分是切片操作符本身,它将表达式分为两个部分,分别由人工读取器和解释器进行解析。因此,我的直觉是,为了突出显示
操作符,应该牺牲与PEP 8的一致性,即,如例3所示,用空格包围操作符。问题是省略表达式两侧的空格是否可以增加可读性:

1. spam[ham(66)/3 : 44+eggs()]
vs


我发现1。解析更快。

我确实看到PEP8中使用了切片:

- Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes. startswith() and endswith() are cleaner and less error prone. For example: Yes: if foo.startswith('bar'): No: if foo[:3] == 'bar': 至于在更复杂的情况下使用哪种方法,我会使用#3。我认为在这种情况下-
方法周围没有空格看起来不好:

spam[ham(66) / 3:44 + eggs()]   # looks like it has a time in the middle. Bad.
如果希望
更加突出,请不要牺牲运算符间距,在
中添加额外的空格:

spam[ham(66) / 3  :  44 + eggs()]   # Wow, it's easy to read!
我不会使用#1,因为我喜欢运算符间距,而#2看起来太像字典
key:value
语法

我也不会叫它接线员。这是构造
切片
对象的特殊语法——您也可以这样做

spam[slice(3, 5)]

正如您已经提到的,PEP8没有明确提到该格式中的slice操作符,但是
spam[3:5]
肯定更常见,而且更具可读性

如果有任何依据,则将标记
之前的空格

[me@home]$ pep8  <(echo "spam[3:44]")   # no warnings
[me@home]$ pep8  <(echo "spam[3 : 44]")  
/dev/fd/63:1:7: E203 whitespace before ':'
然而,我发现上述所有内容都很难用肉眼一目了然地解析

对于PEP8的可读性和遵从性,我个人倾向于:

spam[(ham(66)//3:(44+鸡蛋())]
或对于更复杂的操作:

s_from=ham(66)//3
s_to=44+蛋()
垃圾邮件[s_from:s_to]
spam[slice(3, 5)]
[me@home]$ pep8  <(echo "spam[3:44]")   # no warnings
[me@home]$ pep8  <(echo "spam[3 : 44]")  
/dev/fd/63:1:7: E203 whitespace before ':'
[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 ':'