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… 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:
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:
Or for more complication operations: