DEV Community

qing
qing

Posted on • Edited on

Python Decorators: A Complete Practical Guide

Python Decorators: A Complete Practical Guide

Decorators are a powerful Python feature that lets you modify function behavior without changing the function itself. Here's everything you need to know.

Complete Code Example

import functools
import time

# Basic decorator
def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        print(f"{func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(0.1)
    return "done"

slow_function()  # slow_function took 0.1001s

# Decorator with arguments
def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Python")  # Prints 3 times

# Class-based decorator
class Cache:
    def __init__(self, func):
        self.func = func
        self.cache = {}
        functools.update_wrapper(self, func)

    def __call__(self, *args):
        if args not in self.cache:
            self.cache[args] = self.func(*args)
        return self.cache[args]

@Cache
def fibonacci(n):
    if n < 2: return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(30))  # 832040 (fast due to caching)
Enter fullscreen mode Exit fullscreen mode

💡 Pro Tips

  • Always use @functools.wraps to preserve the original function's metadata
  • Decorators are just syntactic sugar for function composition
  • Use class-based decorators when you need to maintain state

Why This Matters

Understanding these Python features will help you write more:

  • ✅ Readable and maintainable code
  • ✅ Memory-efficient applications
  • ✅ Pythonic, idiomatic solutions

Summary

Mastering Python's built-in features is key to becoming a better developer. Practice these examples in your own projects, and you'll quickly see the benefits.


Found this helpful? Follow me for more Python tutorials and tips! 🐍

Follow for more Python content!


🛠️ Recommended Tool

If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) — $29.99 and designed for developers like you.

Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)