Jump to content
View in the app

A better way to browse. Learn more.

Dynexplorer Community

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Understanding Python Decorators – A Beginner's Guide

Featured Replies

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 caching

  • Improve readability and reusability

Basic Syntax

A 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 Function

import 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 Metadata

Use 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 wrapper

Challenge for You

Try 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.

Guest
Reply to this topic...

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.