record_calls

Python Morsels Exercise

Decorator that records calls to a function

3 bonuses 9 hints 13 solutions 385 users solved 38 reviews

I'd like you to write a decorator function that will record the number of times a function is called.

Your decorator function should be called record_calls and it'll work like this:

@record_calls
def greet(name="world"):
    """Greet someone by their name."""
    print(f"Hello {name}")

That record_calls-decorated greet function will now have a call_count attribute that keeps track of the number of times it was called:

>>> greet("Trey")
Hello Trey
>>> greet.call_count
1
>>> greet()
Hello world
>>> greet.call_count
2

Decorator functions are functions which accept another function and return a new version of that function to replace it.

So this should be the same thing as what we typed above:

greet = record_calls(greet)

If you haven't ever made a decorator function before, you'll want to look up how to make one.

If you've made a decorator function before, you might want to attempt one of the bonuses.

Bonus 1


This is just a preview of the problem statement.

This exercise includes 3 bonuses and 9 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨