2

I would like to create a function keep_running that I could define based on input to either be sensitive to the time that it had been running or the number of iterations. I can't seem to come up with a pythonic way to do the iterations without decrementing the counter outside of the function, e.g.:

def keep_running(ttl):
    return ttl > 0

ttl = 1
while keep_running(ttl):
    do_stuff()
    ttl -= 1

Is there a better way to do this, preferably completely within the function keep_running?

2 Answers 2

2

The best way to manage state is probably inside a class. You could initialize an object loop_context with a ttl value, and then your loop condition would be loop_context.keep_running().

Sign up to request clarification or add additional context in comments.

Comments

2

I am not quite sure about your demand. But iterator might useful for you. Use a iterator, it could be:

>>> def keep_running(ttl):
    while ttl>0:
        yield ttl
        ttl -= 1
>>> for one_round in keep_running(3):
    print(time.time())

Result is:

1365464545.465
1365464545.495
1365464545.505

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.