April 20Apr 20 Decorators are a powerful feature in Python that allow you to modify or extend the behavior of functions or methods without changing their actual code. Think of them as "wrappers" that add functionality before or after the original function runs.Why Use Decorators?Keep your code DRY (Don't Repeat Yourself)Add logging, timing, access control, or cachingImprove readability and reusabilityBasic SyntaxA decorator is just a function that takes another function as an argument and returns a new function.Example: def my_decorator(func): def wrapper(): print("Something is happening before the function.") func() print("Something is happening after the function.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()Output:Something is happening before the function. Hello! Something is happening after the function.Real-World Example: Timing a Functionimport time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start:.4f} seconds") return result return wrapper @timer def slow_function(): time.sleep(2) return "Done" slow_function()Pro Tip: Preserve Function MetadataUse functools.wraps to keep the original function's name and docstring.from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): """Wrapper docstring""" return func(*args, **kwargs) return wrapperChallenge for YouTry writing a decorator that retries a function if it raises an exception. Share your solution below!Happy coding! 🐍
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.