Python Tutorials · Python Functions

Python Decorators

Learn all about Python Decorators in this comprehensive tutorial.

5 min read beginner
  • Decorators let you add extra behavior to a function, without changing the function's code.
  • Define the decorator first, then apply it with @decorator_name above the function.
  • A decorator can be called multiple times.
  • Functions that require arguments can also be decorated, just make sure you pass the arguments to the wrapper function:
  • Decorators can accept their own arguments by adding another wrapper level.
  • You can use multiple decorators on one function.
  • Functions in Python has metadata that can be accessed using the __name__ and __doc__ attributes.

Introduction

Decorators let you add extra behavior to a function, without changing the function's code.

A decorator is a function that takes another function as input and returns a new function.

Basic Decorator

Define the decorator first, then apply it with @decorator_name above the function.

python

By placing @changecase directly above the function definition, the function myfunction is being "decorated" with the changecase function.

The function changecase is the decorator.

The function myfunction is the function that gets decorated.

Multiple Decorator Calls

A decorator can be called multiple times. Just place the decorator above the function you want to decorate.

python

Arguments in the Decorated Function

Functions that require arguments can also be decorated, just make sure you pass the arguments to the wrapper function:

python

*args and **kwargs

python

Decorator With Arguments

Decorators can accept their own arguments by adding another wrapper level.

python

Multiple Decorators

You can use multiple decorators on one function.

This is done by placing the decorator calls on top of each other.

Decorators are called in the reverse order, starting with the one closest to the function.

python

Preserving Function Metadata

Functions in Python has metadata that can be accessed using the __name__ and __doc__ attributes.

python

But, when a function is decorated, the metadata of the original function is lost.

python

To fix this, Python has a built-in function called functools.wraps that can be used to preserve the original function's name and docstring.

python

Module quiz

2 questions
1

Which of the following is true about Python Decorators?

2

What is the most common pitfall when working with Python Decorators?

Answer all questions to submit.