Billjk Billjk - 26 days ago 11
Python Question

Find Out If a Function has been Called

I am programming in Python, and I am wondering if i can test if a function has been called in my code

def example():
pass
example()
#Pseudocode:
if example.has_been_called:
print("foo bar")


How would I do this?

agf agf
Answer

If it's OK for the function to know its own name, you can use a function attribute:

def example():
    example.has_been_called = True
    pass
example.has_been_called = False


example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")

You could also use a decorator to set the attribute:

import functools

def trackcalls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.has_been_called = True
        return func(*args, **kwargs)
    wrapper.has_been_called = False
    return wrapper

@trackcalls
def example():
    pass


example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")