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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With