decorator
In Python, a decorator is a callable that takes another callable as an argument and modifies its behavior without modifying its implementation, returning a new callable.
Decorators are a form of metaprogramming, meaning they allow you to write code that manipulates other code.
Decorators are particularly useful for adding features to your functions, such as logging, authentication, or caching, in a clean and readable manner.
Syntax
@decorator_name
def decorated_function():
...
To apply a decorator to a function, you use the @decorator_name
syntax just before the function’s definition. The decorator takes the original function as an argument, processes it, and returns a function object with extended behavior.
Example
Here’s a quick example of using a decorator to log the execution of a function:
>>> def logger(func):
... def wrapper():
... print("Something is happening before the function is called.")
... func()
... print("Something is happening after the function is called.")
... return wrapper
...
>>> @logger
... def greet():
... print("Hello!")
...
>>> greet()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
In this example, @logger
is a decorator that wraps the greet()
function. When you call greet()
, the wrapper function will print messages before and after the call.
Related Resources
Tutorial
Primer on Python Decorators
In this tutorial, you'll look at what Python decorators are and how you define and use them. Decorators can make your code more readable and reusable. Come take a look at how decorators work under the hood and practice writing your own decorators.
For additional information on related topics, take a look at the following resources:
- Defining Your Own Python Function (Tutorial)
- Python Closures: Common Use Cases and Examples (Tutorial)
- Python's .__call__() Method: Creating Callable Instances (Tutorial)
- Logging in Python (Tutorial)
- Python Decorators 101 (Course)
- Decorators (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Python Closures: Common Use Cases and Examples (Quiz)
- Logging Inside Python (Course)
- Logging in Python (Quiz)