Python Syntax
Lesson 6 of 12 in Coddy's Python Decorators course.
In the previous lesson, we saw how to create function decorators, however, Python provides a much more elegant way to achieve this functionality using @ symbol.
For example,
def my_decorator(func):
def wrapper():
print("Before function is called.")
func()
print("After function is called.")
return wrapper
@my_decorator
def my_function():
print("Inside my_function.")When we run my_function(), we'll see output like this:
Before function is called.
Inside my_function.
After function is called.This shows that the decorator function my_decorator was able to modify the behavior of my_function by adding some extra code before and after it was called.
Challenge
EasyYou are given a code for a function add.
Your task is to write a function decorator named debug, as in the last lesson, but with some additions:
- Append the function decorator
debugtoaddusing the@symbol. - The debug function should support function arguments.
To support function with arguments in a decorator,
def my_decorator(func):
def wrapper(a, b):
print("Before function is called.")
func(a, b)
print("After function is called.")
return wrapperExample:
For a function call add(2, 3), should be printed,
Calling add with arguments (2, 3)
add returned: 5Try it yourself
# Write code here
def add(a, b):
return a + b