All Posts

Python Decorators

Python Decorators

Python decorator is a special type of function that allows you to modify or enhance another function without changing its actual code. Decorators are often used for logging, access control, etc.

Why Use Decorators?

  • To add extra behavior to functions or methods.
  • To follow the DRY (Don’t Repeat Yourself) principle.
  • To make the code cleaner and more readable.

Basic Syntax


def decorator_function(original_function):
    def wrapper_function():
        print("Wrapper executed before", original_function.__name__)
        return original_function()
    return wrapper_function

@decorator_function
def say_hello():
    print("Hello!")

say_hello()

How It Works

When you use @decorator_function above say_hello(), it is the same as:

say_hello = decorator_function(say_hello)

Decorators with Arguments


def decorator_with_args(func):
    def wrapper(*args, **kwargs):
        print("Arguments passed:", args, kwargs)
        return func(*args, **kwargs)
    return wrapper

@decorator_with_args
def greet(name):
    print("Hello", name)

greet("Alice")

Built-in Decorators

  • @staticmethod – Defines a static method in a class.
  • @classmethod – Defines a class method.
  • @property – Used to make methods behave like attributes.

Decorators are a powerful feature in Python that help add functionality to functions in a clean and elegant way.

 

Python Tutorials

Python Tutorial on this website can be found at: