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 wrapperIn 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
EasyWrite 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, usefunc.__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: HelloYou can assume all the functions passed to
debugare no-arguments functions.
Try it yourself