Skip to content

Metaclass

In one line

A metaclass is a class whose instances are classes. It controls class creation and behavior.

In simple words

In Python, everything is an object, and classes are objects too. A metaclass is the class that creates classes. By default, the metaclass is type.

When you write class Foo:, Python calls type('Foo', (), {...}) to create the class. You can customize this by defining your own metaclass to enforce rules, auto-register classes, or modify class attributes at creation time.

Metaclasses are advanced — most developers never need them. They're useful for frameworks (like Django ORM, SQLAlchemy) that need to transform class definitions automatically.

Example

python
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Database(metaclass=SingletonMeta):
    def __init__(self):
        self.connected = True

db1 = Database()
db2 = Database()
print(db1 is db2)  # True — same instance

This metaclass enforces the Singleton pattern — only one instance of any class using it can ever exist.

Common confusions

  • Confused with: class decorator

    The difference: A metaclass controls class creation itself and can affect all subclasses. A class decorator runs after the class is fully created and must be applied to each class individually.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary