Metaclass
- Python course
- Expert
- Lesson 2/47
- 5 min
Learn metaclasses with class Meta(type).
What is a metaclass?
A metaclass is a class that produces classes. You write your own with class Meta(type). When a class is defined with metaclass=Meta, its creation is controlled by Meta.__new__.
The metaclass overrides __new__(mcs, name, bases, ns) where ns is the class namespace. You can add attributes, change methods. type itself is a metaclass; all classes derive from it.
Changing class structure with __new__
In a metaclass __new__ runs before the class object is created. You can add entries to the namespace dict (ns); they become class attributes.
For example ns["created_at"] = "meta" makes created_at appear on the class. You call super().__new__(mcs, name, bases, ns) to produce the actual class object. This pattern powers tools like the Django ORM.
Practice Build a class with the Meta metaclass
Write a Meta(type) metaclass. In __new__(mcs, name, bases, ns) add the key "created_at" with value "meta" to ns, then return super().__new__. Define a User class with metaclass=Meta. Print User.created_at.
Starter code
# Write the Meta metaclass
# add an attribute via __new__
# define User using this metaclassSample solution
# Write the Meta metaclass
class Meta(type):
def __new__(mcs, name, bases, ns):
ns["created_at"] = "meta"
return super().__new__(mcs, name, bases, ns)
class User(metaclass=Meta):
pass
print(User.created_at)Expected output
meta
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the metaclass definition
class Meta(____):
pass
class Meta(type):
pass
Explanation: A metaclass derives from type.
2 When is a metaclass __new__ called?
class Meta(type):
def __new__(mcs, *a):
print("creating")
return super().__new__(mcs, *a)
class A(metaclass=Meta):
pass- When class A is defined
- When A() is called
- When the program starts
- When Meta() is called Correct answer
Explanation: __new__ runs during class definition, i.e. when Meta is called.
3 Match metaclass concepts
| Term | Meaning |
|---|---|
Meta |
Derives from type |
__new__ |
Produces the class |
mcs |
The metaclass itself |
ns |
Namespace dict |