v9.1.1
Menu

Decorator Implementation

mediumFREEFunctionsPython DecoratorsPython Foundations

Problem Statement

Implement a simple function decorator.

Background

Decorators wrap functions to add behavior:

@decorator
def func():
    pass
# Equivalent to: func = decorator(func)

Your Task

Write a decorator call_counter that counts how many times a function is called.

The decorated function should have an attribute call_count that tracks the count.

Output Format

The decorated function should work normally but have a call_count attribute.

Example

Input
Call greet twice
Output
call_count = 2
Reasoning
  • Input: func is any ordinary function, here greet, which takes one name and returns a greeting. Decorating it replaces the name greet with whatever call_counter returns.
  • Output: a function that answers exactly as the original would, so greeting Alice still gives Hello, Alice!, but that also carries a call_count attribute recording how many calls it has received.
  • Trace: right after decoration nobody has called it yet, so the count is 00. The call with Alice returns Hello, Alice! and the count becomes 11; the call with Bob returns Hello, Bob! and it becomes 22. After nn calls the count is nn, so the sample ends at call_count = 2.
  • Notice: the count must live on the function the learner gets back, since that is what the name greet now refers to. Each decorated function keeps its own independent tally: decorating a second function and calling it three times gives it a count of 33 without disturbing the 22 on greet.

Constraints

  • Preserve the original function's behavior
  • Add call_count attribute to the wrapper

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.