Learn how Python decorators work with practical examples and use cases
Table of Contents
Python decorators are a powerful feature that allows you to modify or enhance functions and methods. Let’s dive into how they work and when to use them.
What Are Decorators?
A decorator is a function that takes another function as input and extends its behavior without explicitly modifying it. They’re commonly used for:
- Logging
- Authentication/authorization
- Caching/memoization
- Rate limiting
- Input validation
Basic Decorator Example
Here’s a simple decorator that logs function calls:
| |
Output:
Calling greet
Hello, Alice!
Finished greet
How It Works
When you use @log_calls, Python does this behind the scenes:
| |
The decorator wraps the original function with additional functionality.
Decorators with Arguments
You can create decorators that accept arguments:
| |
Output:
Hello!
Hello!
Hello!
Practical Example: Timing Decorator
Here’s a useful decorator for measuring function execution time:
| |
Note: Always use @wraps(func) from functools to preserve the original function’s metadata.
Class-Based Decorators
You can also create decorators using classes:
| |
Common Built-in Decorators
Python provides several useful built-in decorators:
@property- Create getter methods@staticmethod- Define static methods in classes@classmethod- Define class methods@functools.lru_cache- Memoize function results
Best Practices
- Use
@functools.wrapsto preserve function metadata - Keep decorators simple and focused
- Document decorator behavior clearly
- Consider performance implications
- Chain decorators carefully (order matters!)
Conclusion
Decorators are a elegant way to modify function behavior in Python. They promote code reuse and separation of concerns. Start using them in your projects to write cleaner, more maintainable code!
Have questions or suggestions? Let me know in the comments!