Primer on Python Decorators

Python decorators allow you to modify or extend the behavior of functions and methods without changing their actual code. When you use a Python decorator, you wrap a function with another function, which takes the original function as an argument and returns its modified version. This technique provides a simple way to implement higher-order functions in Python, enhancing code reusability and readability.

By the end of this tutorial, you’ll understand that:

  • Practical use cases for decorators include logging, enforcing access control, caching results, and measuring execution time.
  • Custom decorators are written by defining a function that takes another function as an argument, defines a nested wrapper function, and returns the wrapper.
  • Multiple decorators can be applied to a single function by stacking them before the function definition.
  • The order of decorators impacts the final output since each decorator wraps the next, influencing the behavior of the decorated function.

You can find all the examples from this tutorial by downloading the accompanying materials below:

Take the Quiz: Test your knowledge with our interactive “Primer on Python Decorators” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Primer on Python Decorators

In this quiz, you’ll revisit the foundational concepts of what Python decorators are and how to create and use them.

Python Functions

In order to understand decorators, you must first understand some finer points of how functions work. There are many aspects to functions, but in the context of decorators, a function returns a value based on the given arguments. Here’s a basic example:

Language: Python

>>> def add_one(number):
...     return number + 1
...

>>> add_one(2)
3

In general, functions in Python may also have side effects rather than just turning an input into an output. The print() function is an example of this: it returns None while having the side effect of outputting something to the console. However, to understand decorators, it’s enough to think about functions as tools that turn given arguments into values.

First-Class Objects

In functional programming, you work almost entirely with pure functions that don’t have side effects. While not a purely functional language, Python supports many functional programming concepts, including treating functions as first-class objects.

This means that functions can be passed around and used as arguments, just like any other object like str, int, float, list, and so on. Consider the following three functions:

Language: Python
Filename: greeters.py

def say_hello(name):
    return f"Hello {name}"

def be_awesome(name):
    return f"Yo {name}, together we're the awesomest!"

def greet_bob(greeter_func):
    return greeter_func("Bob")

Here, say_hello() and be_awesome() are regular functions that expect a name given as a string. The greet_bob() function, however, expects a function as its argument. You can, for example, pass it the say_hello() or the be_awesome() function.

To test your functions, you can run your code in interactive mode. You do this with the -i flag. For example, if your code is in a file named greeters.py, then you run python -i greeters.py:

Language: Python

>>> greet_bob(say_hello)
'Hello Bob'

>>> greet_bob(be_awesome)
"Yo Bob, together we're the awesomest!"

Note that greet_bob(say_hello) refers to two functions, greet_bob() and say_hello, but in different ways. The say_hello function is named without parentheses. This means that only a reference to the function is passed. The function isn’t executed. The greet_bob() function, on the other hand, is written with parentheses, so it will be called as usual.

This is an important distinction that’s crucial for how functions work as first-class objects. A function name without parentheses is a reference to a function, while a function name with trailing parentheses calls the function and refers to its return value.

Inner Functions

It’s possible to define functions inside other functions. Such functions are called inner functions. Here’s an example of a function with two inner functions:

Language: Python
Filename: inner_functions.py

def parent():
    print("Printing from parent()")

    def first_child():
        print("Printing from first_child()")

    def second_child():
        print("Printing from second_child()")

    second_child()
    first_child()

Read the full article at »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Similar Posts

Leave a Reply