remove-redundant-slice-index
Removes unnecessary explicit 0
when slicing the beginning of a sequence.
With an end index:
numbers[0:5]
Without an end index:
numbers[0:]
With an end index:
numbers[:5]
Without an end index:
numbers[:]
The default starting value for a slice is 0, so it is unnecessary to explicitly define it. This refactoring removes such zeros, slightly shortening the code.
remove-unused-enumerate
Remove unnecessary calls to
enumerate
when
the index variable is not used.
for index, hat in enumerate(hats):
print("I like this hat: ", hat)
for i, (key, value) in enumerate(my_dictionary.items(), start=100):
do_something(key)
do_something_else(value)
for hat in hats:
print("I like this hat: ", hat)
for key, value in my_dictionary.items():
do_something(key)
do_something_else(value)
Enumerating iterables with
enumerate
is a
good practice for having access to both the values and their respective indices.
However, when the indices are not necessary, it is cleaner to simply iterate
over the original iterable and remove the call to enumerate
.
simplify-string-len-comparison
Changes an indirect comparison of a string's length to 0
into a direct
comparison of the string to the empty string.
if len(s) == 0:
...
if len(r) > 0:
...
if s == "":
...
if r != "":
...
This refactoring avoids an unnecessary calculation and keeps the logic in the domain of string types. It tends to unlock further improvements to string comparisons.
useless-else-on-loop
Moves code in else
blocks that is always executed to the main body
evens = []
for n in numbers:
if n % 2:
evens.append(n)
else:
print("Done!")
evens = []
for n in numbers:
if n % 2:
evens.append(n)
print("Done!")
Loops should only have an else
clause if they can exit early with a break
statement. If there is no break
then the code in the else
is always
executed. In this case the else
statements can be moved to the same scope as
the loop itself, making the code slightly easier to understand (no need to look
up what the else
does).
simplify-len-comparison
proposal has been extended to cover cases such
as len(seq) != 0
remove-redundant-if
was incorrectly suggested in situations
with nested changes to condition variablesuse-any
could be incorrectly suggested in cases where the
for
loop being replaced unpacked and used multiple variables