Python Metaclasses Cheat Sheet
Covers how Python classes are created via type, writing custom metaclasses, and when to reach for simpler alternatives instead.
1 PageAdvancedApr 12, 2026
Classes Are Created by type
Every class is itself an instance of a metaclass.
python
class Foo: x = 1# Foo is itself an instance of typeprint(type(Foo)) # <class 'type'>print(isinstance(Foo, type)) # True# You can build an equivalent class dynamically with type()Foo2 = type("Foo2", (), {"x": 1})print(Foo2().x) # 1# type(name, bases, namespace) is exactly what the `class` statement calls
Writing a Metaclass
Hook into class creation itself, not just instance creation.
python
class Meta(type): def __new__(mcs, name, bases, namespace): # Runs before the class object is created for key, value in namespace.items(): if callable(value) and not key.startswith("__"): print(f"defining method: {key}") return super().__new__(mcs, name, bases, namespace) def __init__(cls, name, bases, namespace): # Runs after the class object is created super().__init__(name, bases, namespace)class MyClass(metaclass=Meta): def greet(self): return "hi"# Prints "defining method: greet" at class-definition time
Practical Use: Enforcing a Pattern
Metaclasses can enforce rules across all subclasses.
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 Config(metaclass=SingletonMeta): def __init__(self): self.settings = {}a = Config()b = Config()assert a is b # Same instance every time
Key Concepts
Core vocabulary for metaclass programming.
- type- The default metaclass; type(obj) returns an object's class, type(cls) returns its metaclass
- metaclass=- Class keyword argument that specifies which metaclass builds the class
- __new__- On a metaclass, controls creation of the class object itself, not instances
- __init_subclass__- A simpler, often sufficient alternative to a metaclass for customizing subclasses
- __class_getitem__- Enables MyClass[int] generic subscript syntax without a metaclass
- ABCMeta- Standard-library metaclass (abc module) used to define abstract base classes
Pro Tip
Reach for __init_subclass__ or a class decorator before writing a metaclass. As Tim Peters put it, 'metaclasses are deeper magic than 99% of users should ever worry about' — most registration or validation needs don't actually require one.
Was this cheat sheet helpful?
Explore Topics
#PythonMetaclasses#PythonMetaclassesCheatSheet#Programming#Advanced#ClassesAreCreatedByType#WritingAMetaclass#PracticalUseEnforcingAPattern#KeyConcepts#OOP#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance