Lesson 39 of 4098%

(Progress persistence is disabled until Phase 9)

Python
Intermediate

Decorators

Modify the behavior of functions.

Decorators

What You’ll Learn

You’ll learn how to use decorators to modify or enhance the behavior of a function without changing its source code.

Higher-Order Functions

In Python, functions are first-class objects. This means functions can be passed around and used as arguments, just like any other object (string, int, float, list, and so on).

What is a Decorator?

A decorator takes in a function, adds some functionality, and returns it. It’s marked with the @ symbol.

# The Decorator
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

# Applying the Decorator
@my_decorator
def say_hello():
    print("Hello!")

# Calling the function
say_hello()

Expected Output:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

Decorators are widely used in frameworks like Flask or Django to check if a user is logged in before allowing them to view a page.

Lesson Progress

Take QuizBuild a Python Project