Menu
Coddy logo textTech

Decorators Usage

Lesson 5 of 12 in Coddy's Python Decorators course.

In Python, a decorator is a function that takes another function as input and extends the behavior of the input function without explicitly modifying its code. Decorators are a powerful way to modify or enhance the behavior of functions in a flexible and reusable way.

Here's an example of a simple decorator function:

def my_decorator(func):
    def wrapper():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return wrapper

In this example, the my_decorator function takes another function func as input and returns a new function called wrapper.

The wrapper function adds some behavior before and after the func function is called.

challenge icon

Challenge

Easy

Write a decorator function called debug that takes a function func as input and returns a new function that prints the name of func and the return value of func every time it is called.

To get the name of func, use func.__name__.

Here's an example of the use of the debug decorator:
 

def hello():
    return "Hello"

debug_hello = debug(hello)
debug_hello()

In this example, we're using the debug decorator to wrap the hello function and create a new function called debug_hello. When we call debug_hello(), the decorator will print:

Calling hello
hello returned: Hello

You can assume all the functions passed to debug are no-arguments functions.

Try it yourself

All lessons in Python Decorators