0

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?

Matt
  • 14,906
  • 27
  • 99
  • 149
Satoshi
  • 13
  • 4

3 Answers3

2

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)
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • Thanks!That's great!Also I can have multiple decorators for 1 function right? – Satoshi Mar 19 '14 at 16:29
  • @Satoshi Usually, because a decorator usually returns a function with the same or similar signature. But the real answer is *it depends*. A decorator can completely change the nature of a function, even return a non-function, so the next decorator won't know what to do with it. – kojiro Mar 19 '14 at 17:05
0
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...

scav
  • 1,095
  • 1
  • 9
  • 17
0

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()
roippi
  • 25,533
  • 4
  • 48
  • 73