Start New Discussion within our Software Development Community

"""2) When testing software, it can be useful to count the number of times that
a function is called. Without using any lists or dictionaries, define a
higher-order function count_calls that returns two functions:

- a counted version of the original function that counts the number of times
it has been called

- a function of zero arguments that returns the number of times that the
counted function is called

def count_calls(f):
    """A decorator that returns a version of f that counts calls to f and can
    report that count to how_many_calls.

    >>> from operator import add
    >>> counted_add, add_count = count_calls(add)
    >>> add_count()
    >>> counted_add(1, 2)
    >>> add_count()
    >>> add(3, 4)  # Doesn't count
    >>> add_count()
    >>> counted_add(5, 6)
    >>> add_count()
    "*** My CODE HERE ***"
    total = 0
    def counted_function():
        f1 = f
        nonlocal total
        total = total + 1
        return f1
    def function_count():
        nonlocal total
        return total
    return counted_function,function_count

so the problem i am facing is that i can basically do what i am required to do but my function calls need to be as counted_add()(1,2) instead of counted_add(1,2) how do i go about solving that ? i mean i tried changing the return to counted_function(),function_count but than i call the function only once and total never increments. help appreciated

This article has been dead for over six months. Start a new discussion instead.