Python's decorators are an advanced construct in the Python language that sometimes trips up people who are new to programming. It can take a while to wrap your head around them, but getting a high-level understanding will help you step up your game in Python.
How Do Python Decorators Work?
Decorators allow you to extend the behavior of a function without modifying it. Decorators are commonly used when working with web frameworks such as Flask or Django, but you can also apply them in other scenarios and even write your own decorators.
Decorator Example
To get started, copy the following example into a script and run it on your computer:
def lowercase(func):
"""A decorator that avoids digital screaming."""
def wrapper(text):
initial_result = func(text)
new_result = initial_result.lower()
return new_result
return wrapper
@lowercase
def say_something(text):
return text
print(say_something("HEY WHAT'S UP?")) # OUTPUT: hey what's up?
Don't worry about understanding the code as of now. You'll pick it apart piece by piece over the course of this section. For now, just play around with the input to say_something(). You'll notice that any text that you pass will get converted to lowercase. And that's despite the fact that there's no code doing that inside the function definition of say_something()!
You're seeing the power of decorators in action. After defining the lowercase() decorator, you can add it to any function definition with the @decorator syntax, and that function will be modified without you needing to change any of its code.
Tasks
- Copy the code snippet to a Python script and execute it.
- Write a second function that returns some text and wraps it with the
lowercasedecorator in the same way thatsay_somethingis wrapped in the example code. - Call the second function with some uppercase text as input and inspect its output to confirm that it has also been converted to lowercase.
What You Will Learn
In this section of the course, you'll roll up your sleeves to roll up the concepts that are important for understanding Python decorators. Since it's a challenging topic, you'll tackle the concepts broken up into five steps:
- Functions
- Scopes
- Arguments
- Empty decorators
- Decorators
You already got to know most of these concepts, but in these lessons, you'll learn how they apply to Python decorators specifically. You'll begin with a revisit of functions as Python objects.
Additional Resources
- The official PEP: PEP-0318
- A historical perspective on Python decorators: Python Decorators
Summary: Introduction to Python Decorators
- Decorators extend the behavior of a function without modifying it
- Decorators are commonly used with web frameworks
Five Concepts You Will Learn in this Section
- Functions
- Scopes
- Arguments
- Empty decorators
- Decorators