sourcery
sourcery copied to clipboard
Replace while with for refactoring could go one step further
Issue description or question
Consider this as a suggestion. The refactoring could go a step further when these two rules are used together.
Replace while with for (while-to-for) Replace unused for index with underscore (for-index-underscore)
When the two refactoring actions are combined together, they can result in
def wait_for_status():
timeout = 300 # 5 minutes
while timeout > 0:
timeout -= 30
time.sleep(30)
def wait_for_status():
for _ in range(300, 0, -30):
time.sleep(30)
or
def wait_for_status():
retries = 5
while retries > 0:
retries = retries - 1
time.sleep(10)
def wait_for_status():
for _ in range(5, 0, -1):
time.sleep(10)
I understand it can be tricky, but a simpler form would be
for _ in range(10):
for _ in range(5):
as the value of index is not used
I simplified the examples. As is, the rules were very useful and the last optimization was quite straight forward.
Sourcery Version
v0.11.4
Code editor or IDE name and version
VSCode 1.66.2
OS name and version
Windows 10 running WSL Linux - Alpine 3.14..0.1
Hi @lonico, this is an excellent suggestion, and I'll add it to our pipeline for a future release.