DEV Community

qing
qing

Posted on • Edited on

Master Python Decorators

2-Minute Python Guide: Decorators
Hey fellow coders! Let's dive into one of Python's most powerful features: decorators. So, what does a decorator do? In a nutshell, it's a function that modifies or extends the behavior of another function without permanently changing it. Think of it like wrapping a gift - you're adding something extra to the original present without altering its core.

Here's a minimal example of a timer decorator:

import time
from functools import wraps

def timer_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds to run.")
        return result
    return wrapper

@timer_decorator
def example_function():
    time.sleep(1)  # simulate some work

example_function()
Enter fullscreen mode Exit fullscreen mode

In this example, the timer_decorator function takes in a function (example_function), measures the time it takes to run, and then prints out the result. The @timer_decorator line above example_function is just a shorthand way of saying example_function = timer_decorator(example_function).

Takeaway: Decorators are a game-changer for writing reusable, modular code. They let you add functionality to existing functions without modifying their source code, making your code more flexible and maintainable. Give them a try and see how they can supercharge your Python projects!


Follow me on Dev.to for daily Python tips and quick guides!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


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


If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.

Top comments (0)