If it were not for the time.sleep
, your loop would be equivalent to
for _ in range(max_limit):
if <condition>:
return True
# time.sleep(10)
return False
Which is equivalent to return any(<condition> for _ in range(max_limit)
.
Thus, you could (ab)use any
and or
to check whether the condition is met up to a certai number of times while waiting a bit before each check:
any(time.sleep(10) or <condition> for _ in range(max_limit))
This will first evaluate time.sleep
, which returns None
, and then evaluate the condition, until the condition is met or the range
is exhausted.
The only caveat is that this will call time.sleep
even before the first check of the condition. To fix this, you can first check the counter variable and only if that is > 0
call time.sleep
:
any(i and time.sleep(10) or <condition> for i in range(10))
Whether that's clearer than the long loop is for you to decide.
As suggested in comments, you can in fact just invert the above any
clause to
any(<condition> or time.sleep(10) for _ in range(max_limit))
This will first check the condition and only if the condition is false will sleep
. It also ready much more naturally than any of the above two appraoches.