Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Out If a Function has been Called

Tags:

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?

like image 402
Billjk Avatar asked Mar 27 '12 01:03

Billjk


People also ask

How do you check if a function has been called?

You can log a message when the function is called using: Debug. Log("Function called!"); You can store a bool that starts as false and set it to true when you enter the function. You can then check this bool elsewhere in code to tell whether your function has been called.

When a function is called in Python?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.


2 Answers

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") 
like image 122
agf Avatar answered Sep 28 '22 09:09

agf


We can use mock.Mock

from unittest import mock   def check_called(func):     return mock.Mock(side_effect=func)   @check_called def summator(a, b):     print(a + b)   summator(1, 3) summator.assert_called() assert summator.called == True assert summator.call_count > 0  summator.assert_called_with(1, 3)  summator.assert_called_with(1, 5)  # error # AssertionError: Expected call: mock(1, 5) # Actual call: mock(1, 3) 
like image 44
Nick Korolkov Avatar answered Sep 28 '22 09:09

Nick Korolkov