I didn't find this kind of question anywhere so I'm going to ask it here.
How can I check if some specific function written by me wasn't called for some x amount of time?
I didn't find this kind of question anywhere so I'm going to ask it here.
How can I check if some specific function written by me wasn't called for some x amount of time?
You could embed the last called time in the function definition:
def myfun():
myfun.last_called = datetime.now()
# … do things
From this point it should be easy to tell when the function was called. Each time it's called it will update its last_called timestamp.
A more general approach would be to define a function decorator to attach the property:
def remembercalltimes(f, *args, **kwargs):
"""A decorator to help a function remember when it was last called."""
def inner(*args, **kwargs):
inner.last_called = datetime.now()
return f(*args, **kwargs)
return inner
@remembercalltimes
def myfun():
# … do things
>>> myfun()
>>> myfun.last_called
>>> datetime.datetime(2014, 3, 19, 11, 47, 5, 784833)
import time
last_time_f_called = time.time()
def f():
global last_time_f_called
now = time.time()
time_since = now - last_time_f_called
last_time_f_called = now
# do whatever you wanted to do about value of time_since
Something like that?
You could probably wrap that in a decorator that updated times in a dict, where key was the function name, if it was the sort of thing you wanted to do a lot...
This seems like a reasonable time to plop that info in the function's __dict__
, maybe with a decorator.
def lastcalled(func):
def inner():
from datetime import datetime
then = func.__dict__.get('lastcalled')
diff = int((datetime.now() - then ).total_seconds()) if then else None
print('Last called: {}'.format('{} sec ago'.format(diff) if diff else 'Never'))
func()
func.lastcalled = datetime.now()
return inner
demo:
@lastcalled
def f():
print('printing in f()')
f()
Last called: Never
printing in f()
#wait 5 seconds
f()
Last called: 5 sec ago
printing in f()