Decorator basics
- Python course
- Intermediate
- Lesson 36/116
- 5 min
Learn how decorators work.
What is a decorator?
A decorator is a tool that wraps a function or class to extend its behavior without changing it. In Python a decorator is written as @name directly above the target.
Example: @log\ndef hello():\n .... Here the log decorator takes the hello function and wraps it with a new function. The call is still hello() but the wrapped function runs under the hood. Decorators collect repeated tasks (logging, caching, permissions) in one place.
Decorator syntax
A decorator is written as @decorator_name on the line right before the function definition. When Python sees this line it automatically calls target = decorator_name(target).
Example: @upper\ndef hello():\n return "hi". This is equivalent to hello = upper(hello). The decorator takes the incoming function and returns a new function. After the call, hello refers to the wrapped version.
Practice Add a decorator line
Define a decorator named with_log. With signature def with_log(fn):, write def wrapper(): inside; its body should have print("calling") and return fn(). Return the wrapper with return wrapper. Then decorate with @with_log and define def hello(): with body return "hi". Finally call print(hello()).
Starter code
# Write the with_log decorator and the hello functionSample solution
# Write the with_log decorator and the hello function
def with_log(fn):
def wrapper():
print("calling")
return fn()
return wrapper
@with_log
def hello():
return "hi"
print(hello())Expected output
calling hi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does @name do?
- Passes the function through inheritance
- Deletes the function
- Wraps the function below with another function Correct answer
- Renames the function
Explanation: @name wraps the target function with the decorator function.
2 Complete the decorator line
def hello():
return "hi"
____
def big_hello():
return hello().upper()
def hello():
return "hi"
@big_hello
def big_hello():
return hello().upper()
Explanation: The line starting with @ binds the decorator.
3 Match the decorator parts
| Term | Meaning |
|---|---|
@ |
Decorator sign |
name |
Decorator function |
def target(): |
Decorated function |
target = name(target) |
Equivalent assignment |