Python Decorators
Python decorators are one of the most powerful and useful tools in the language. They allow you to modify or enhance the behavior of functions or classes without permanently changing their source code. If you’ve already learned about Python Generators & Itertools, decorators are the next big step in mastering advanced Python concepts.
What Are Decorators?
A decorator in Python is essentially a function that takes another function as input and extends or modifies its behavior without explicitly changing it. They’re often used for logging, authentication, measuring execution time, and more.
Functions Are First-Class Objects
In Python, functions are treated as first-class objects. This means you can:
- Assign them to variables
- Pass them as arguments to other functions
- Return them from functions
def greet(name):
return f"Hello, {name}"
say_hello = greet
print(say_hello("Python"))
Output:
Hello, Python
Nested Functions & Closures
Decorators rely heavily on the idea of nested functions and closures. Let’s see how:
def outer_function():
def inner_function():
return "This is inner"
return inner_function
func = outer_function()
print(func())
Output:
This is inner
Creating a Simple Decorator
A decorator is just a function that takes another function and returns a new one.
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function
def display():
print("Display function ran")
decorated_display = decorator_function(display)
decorated_display()
Output:
Wrapper executed before display
Display function ran
Using the @decorator Syntax
Python provides a special syntax using @
to apply decorators directly to functions.
def my_decorator(func):
def wrapper():
print("Something before the function.")
func()
print("Something after the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Something before the function.
Hello!
Something after the function.
Decorators with Arguments
Decorators can also accept arguments, which makes them more powerful.
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Python")
Output:
Hello, Python!
Hello, Python!
Hello, Python!
Multiple Decorators
You can stack multiple decorators on a single function.
def decorator_one(func):
def wrapper():
print("Decorator One")
func()
return wrapper
def decorator_two(func):
def wrapper():
print("Decorator Two")
func()
return wrapper
@decorator_one
@decorator_two
def show():
print("Function Called")
show()
Output:
Decorator One
Decorator Two
Function Called
Real-Life Use Cases of Decorators
- Logging: Automatically log function calls.
- Authentication: Check if a user has access rights.
- Timing: Measure how long a function takes to run.
- Memoization: Cache results of expensive function calls.
Comparison Table: Function vs Decorator
Aspect | Normal Function | Decorator |
---|---|---|
Definition | Executes a task | Enhances another function |
Input | Arguments & data | Another function |
Use Case | Perform operation | Logging, auth, timing |
Exercises
- Create a decorator that logs the name of every function before running it.
- Write a decorator that measures execution time of a function.
- Use a decorator with arguments to repeat a function N times.
FAQ
Q1. Can a decorator be applied to multiple functions?
Yes, you can apply the same decorator to multiple functions.
Q2. What’s the difference between yield and decorators?yield
is for generators, while decorators modify functions dynamically.
Q3. Are decorators only for functions?
No, decorators can also be applied to classes.
Conclusion
Python decorators are a key concept in advanced programming. They make code cleaner, reusable, and more maintainable. From simple logging to powerful frameworks like Flask and Django, decorators are everywhere in Python. Mastering them takes you one big step closer to professional-level coding.
🔗 Related Reads:
- Python Programming: A Beginner’s Guide
- Python Variables
- Python Data Types
- Python Strings
- Python Operators
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python If...Else Statements and Conditions
- Python Match Statement
- Python Functions
- Python Lambda
- Python Arrays
- Python Classes & Objects
- Python Inheritance
- Python Iterators
- Python Polymorphism
- Python Scope
- Python Modules
- Python Datetime
- Python Math
- Python Exception Handling
- Python File Handling
- Python Generators & Itertools
0 Comments