Back to Python Mastery
AdvancedAdults

Decorators

Decorators are a powerful and flexible way to modify or enhance functions without permanently changing their code. A decorator is a function that takes another function as input, adds some functionality to it, and returns the modified function.

They are often used for logging, timing, and enforcing access control.

Here's a simple decorator that prints a message before and after a function runs:

def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper

Now, you can "decorate" another function with it using the @ symbol:

@my_decorator
def say_whee():
print("Whee!")

When you call say_whee(), you'll see the decorator's messages printed around the original function's output. Decorators help keep your code DRY (Don't Repeat Yourself).

Timing a Function

Write a decorator `timer` that prints the time a function takes to execute. The `time` library has been imported for you.