Last modified: Nov 19, 2026

Python Class Decorator Guide

A class decorator is a powerful Python feature. It lets you modify or enhance a class without changing its source code.

Many beginners meet decorators on functions first. Class decorators follow the same idea, but they operate on classes.

This guide explains what class decorators are, how they work, and when to use them. It also includes clear code examples and outputs.

What Is a Class Decorator?

A class decorator is a callable that receives a class object. It returns a class object, usually the same class or a modified version.

The syntax uses the @ symbol above a class definition. Python applies the decorator right after the class is created.

Here is the simplest possible example:


def add_greeting(cls):
    # Add a new method to the class
    cls.greet = lambda self: "Hello from " + cls.__name__
    return cls

@add_greeting
class Robot:
    pass

r = Robot()
print(r.greet())

Hello from Robot

The decorator adds a method to Robot. The class body stays unchanged. This is the core idea of class decorators.

You can also attach metadata, register classes, or wrap methods. The decorator is just a function that receives a class.

Class Decorator vs Function Decorator

A function decorator receives a function. A class decorator receives a class. Both return a callable object.

The mechanics are similar. But class decorators often modify attributes or methods rather than wrap calls.

If you have used a decorator with parameters before, you already know the pattern. The same closure idea applies here, as explained in this guide to a Python decorator with arguments.

One key difference is timing. A class decorator runs after the class body is executed. At that point, the class object exists and can be inspected.

How Python Applies a Class Decorator

Python evaluates the class body first. Then it creates the class object. Then it passes that object to the decorator.

The result replaces the original name in the module namespace. So the decorated class is what you get when you use the name.

This behavior is consistent and predictable. It also means decorators can return a completely different class if needed.

Here is an example that returns a wrapper class:


def log_methods(cls):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self._obj = cls(*args, **kwargs)

        def __getattr__(self, name):
            # Log every method access
            print(f"Accessing: {name}")
            return getattr(self._obj, name)

    return Wrapper

@log_methods
class Calculator:
    def add(self, a, b):
        return a + b

calc = Calculator()
print(calc.add(2, 3))

Accessing: add
5

This pattern is useful for debugging or profiling. It shows how a decorator can wrap the class entirely.

Practical Use Cases for Class Decorators

Class decorators shine in several real-world scenarios. Here are the most common ones.

1. Registering Classes

Frameworks often use decorators to register classes automatically. The decorator adds the class to a global registry.


registry = {}

def register(cls):
    # Store the class by its name
    registry[cls.__name__] = cls
    return cls

@register
class UserHandler:
    pass

@register
class OrderHandler:
    pass

print(list(registry.keys()))

['UserHandler', 'OrderHandler']

This pattern is common in plugin systems. It removes the need for manual registration code.

2. Adding Methods or Attributes

A decorator can inject helper methods. This is handy for adding serialization or comparison behavior.


def add_to_dict(cls):
    def to_dict(self):
        # Build a dictionary from instance attributes
        return self.__dict__.copy()

    cls.to_dict = to_dict
    return cls

@add_to_dict
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.to_dict())

{'x': 1, 'y': 2}

The class gains a new capability with no changes to its body. This keeps concerns separated.

3. Enforcing Rules

Decorators can validate a class at definition time. For example, you can require a specific method to exist.


def require_run(cls):
    if not hasattr(cls, "run"):
        raise TypeError(f"{cls.__name__} must define a run method")
    return cls

@require_run
class Task:
    def run(self):
        print("Running task")

print("Task is valid")

Task is valid

If the method were missing, Python would raise an error at import time. This catches mistakes early.

Working with Method Names and Signatures

Some class decorators inspect methods. You may need the method name or its parameters.

Python provides tools for this. You can retrieve a function's name at runtime with the techniques in this guide on how to get a function name at runtime.

For deeper analysis, you can read parameter details. The Python inspect function signature guide shows how to do that reliably.

This is useful when a decorator wraps methods and needs to preserve arguments. It also helps when generating documentation or validation logic.

Class Decorators and Memoization

Memoization is a common performance technique. It caches results so repeated calls are fast.

You can apply caching to class methods. Python's standard library offers ready-made tools for this.

For a full walkthrough, see Python caching with functools. It explains how to cache function results cleanly.

When caching methods, remember that the first argument is usually self. That affects how cache keys are built.

Here is a small example using a class decorator to cache a method:


from functools import lru_cache

def cache_compute(cls):
    # Wrap the compute method with a cache
    original = cls.compute
    cls.compute = lru_cache(maxsize=None)(original)
    return cls

@cache_compute
class Heavy:
    def compute(self, n):
        print("Calculating...")
        return n * n

h = Heavy()
print(h.compute(4))
print(h.compute(4))

Calculating...
16
16

The second call skips the calculation. The cache returns the stored value.

Be careful with mutable objects as arguments. They are not hashable and will break the cache.

Common Mistakes to Avoid

Class decorators are simple, but a few pitfalls trip up beginners.

First, do not forget to return the class. If you forget, the name becomes None.


def broken(cls):
    cls.extra = True
    # Missing return statement

@broken
class Sample:
    pass

print(Sample)

None

Second, avoid modifying the class in ways that break inheritance. Wrapping the class in a new class hides the original type.

Third, keep decorators focused. A decorator that does too much becomes hard to debug.

Finally, remember that decorators run at import time. Any error inside the decorator stops the program immediately.

Class Decorators and Other Python Features

Class decorators often work alongside other features. Understanding those features makes decorators easier to use.

For example, you may combine decorators with properties. The Python property decorator explained article covers that pattern well.

You may also use inheritance inside decorated classes. The super() function explained guide helps clarify how parent methods are called.

Generators are another useful tool. If a decorated method yields values, the yield vs return key differences article explains the behavior clearly.

These features are independent, but they combine well in larger applications.

Best Practices for Clean Class Decorators

Write decorators that are easy to read. Use clear names and short bodies.

Preserve the original class name and documentation. Use functools.wraps when wrapping functions inside the decorator.

Keep side effects minimal. A decorator should do one job well.

Add comments that explain why the decorator exists. Future readers will thank you.

Test decorated classes like any other class. The decorator is code too, and it can have bugs.

When to Use a Class Decorator

Use a class decorator when you need to modify a class after its definition. It is ideal for registration, validation, and small enhancements.

Avoid it when a base class or mixin is clearer. Decorators are powerful, but they are not always the simplest solution.

If the change is about behavior at call time, a method decorator may fit better. If the change is about the class as a whole, a class decorator is the right tool.

Conclusion

Python class decorators are a clean way to enhance classes. They receive a class and return a class, often with small additions.

They are great for registration, adding methods, enforcing rules, and caching. They also keep your code modular and readable.

Start with simple examples. Then try wrapping methods and adding validation. With practice, class decorators become a natural part of your Python toolkit.

Remember the golden rule: always return the class. That single habit prevents most beginner mistakes.