python way to check for a condition with timeout

python timeout
python wait until condition
python wait for function to finish
python timeout decorator
python timeout loop
python try except timeout
python sleep until
python thread timeout

I need to check for a certain condition before a timeout. If the condition is met before the limit then I return True otherwise I return False.

I'm doing this in the following way

counter = 1
condition_met = False
while counter < max_limit:
    if <conditions are met>:
        condition_met = True
        break
    time.sleep(10)
    counter += 1
return condition_met

I'm wondering if there's a more pythonic way to do the same thing.

Thanks in advance for your feedbacks

A really good way to time things is by using—shock—the time module:

import time

def foo():
    max_limit = 25  # Seconds.

    start = time.time()
    condition_met = False
    while time.time() - start < max_limit:
        if <conditions are met>:
            condition_met = True
            break
        time.sleep(10)

    return condition_met

See? The module is good for more than just sleeping. ;¬)

How To Make Python Wait, Look at CPU usage and note how it goes through the roof. loop iteration, which means that Python will only evaluate the exit condition of the loop but if the thread is stuck in the exit_thread.wait(timeout=10) call at the exact  The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in another thread. Once awakened, it re-acquires the lock and returns. It is also possible to specify a timeout. The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting.

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.

7.5.3 Condition Objects, It is also possible to specify a timeout. The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. The notifyAll()  So, for esxample, if you have a function “doit(‘arg1’, ‘arg2’)” that you want to limit to running for 5 seconds, with func_timeout you can call it like this: from func_timeout import func_timeout, FunctionTimedOut … try: doitReturnValue = func_timeout(5, doit, args=(‘arg1’, ‘arg2’)) except FunctionTimedOut:

I am assuming you have a code in a function. The below code get rid of a variable condition_met and break statement.

counter = 1
# condition_met = False
while counter < max_limit:
    if <conditions are met>:
        # condition_met = True
        return True   # get rid of break statement
    time.sleep(10)
    counter += 1
return False

17.1. threading — Thread-based parallelism, The maximum value allowed for the timeout parameter of blocking functions The wait_for() method can be used to automate the condition checking, and eases  A conditional statement in Python is handled by if statements and we saw various other ways we can use conditional statements like if and else over here. "if condition" – It is used when you need to print out the result when one of the conditions is true or false.

16.2. threading — Thread-based parallelism, The maximum value allowed for the timeout parameter of blocking functions The wait_for() method can be used to automate the condition checking, and eases  The check should always be done when .wait() doesn't time out, and even if .wait() does time out, self._empty() may return false anyway. Note too that .wait()'s caller holds the associated mutex regardless of whether return is due to timeout or notify, and the caller needs to release it again in either case.

How (not) to set a timeout on a computation in Python, How (not) to set a timeout on a computation in Python. August 22, 2011 It turns out this seemingly simple task is hard to do in Python. Here I want to Take a look at it - it's a bag full of solutions for your IO problems. So what  When you call.start () to start a new Python timer, you first check that the timer isn’t already running. Then you store the current value of perf_counter () in._start_time. On the other hand, when you call.stop (), you first check that the Python timer is running.

Python sleep(): How to Add Time Delays to Your Code – Real Python, One way to do this check is to use a Python sleep() system call: import time import urllib.request import urllib.error def sleep(timeout, retry=3):  Python Conditions and If statements. Python supports the usual logical conditions from mathematics: Equals: a == b; Not Equals: a != b; Less than: a < b; Less than or equal to: a <= b; Greater than: a > b; Greater than or equal to: a >= b; These conditions can be used in several ways, most commonly in "if statements" and loops.

Comments
  • Thank you for this tip, it's better that computing a counter and increment it
  • Thanks Tobias, I'm voiceless
  • @Simon I am very sorry to hear that. Or did you mean speechless? ;-)
  • Wouldn't the first solution already work if rewritten as any(<condition> or time.sleep(10) for _ in range(max_limit))?
  • @lekv Absolutely, and it also ready much more naturally. Makes me wonder why I missed that. Thanks! (I think I thought "hm, but we don't know if <condition> will be true or false, so we can't put the or after or it may not be evaluated", but of course that's just how we want it.)
  • You could save two more lines and a variable by just looping for _ in range(max_limix): (assuming counter is not used in the condition)
  • Thanks, indeed you're right but my bad i forgot to add that after the while I print a message whether conditions are met or we reach a timeout but checking condition_met value. Using your solution I'd need to do the check outside my function and at the end it'd almost be the same thing but I prefer yours because it removes a variable
  • @Simon Instead of True and False you can return the message that you want to print.
  • True again but in my case I need to quit my program and print a Warning if False. So I still need to check the value returned.
  • Incrementing a counter isn't a very accurate way of timing something, it's just a count. In this case there is a relationship between elapsed time and loop iterations because of the time.sleep() call in the loop, but in general it will depend on how fast the computer can execute the other statements within the loop. To actually time how long something is or has taken requires determining the amount of time that has elapsed since some starting point.