Search code examples
pythonfunctioncalltime-frequency

Checking if function was not called for 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?


Solution

  • 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)