How to Create Metaclass in Python: Syntax and Examples
In Python, you create a metaclass by defining a class that inherits from
type. You then specify this metaclass in a class definition using the metaclass keyword to control class creation behavior.Syntax
A metaclass is defined by creating a class that inherits from type. You can customize class creation by overriding methods like __new__ or __init__. To use a metaclass, specify it in the class header with metaclass=YourMeta.
- class YourMeta(type): defines the metaclass.
- def __new__(cls, name, bases, dct): controls class creation.
- class YourClass(metaclass=YourMeta): uses the metaclass.
python
class YourMeta(type): def __new__(cls, name, bases, dct): # customize class creation here return super().__new__(cls, name, bases, dct) class YourClass(metaclass=YourMeta): pass
Example
This example shows a metaclass that prints a message when a new class is created. It demonstrates how metaclasses can customize class creation.
python
class VerboseMeta(type): def __new__(cls, name, bases, dct): print(f"Creating class {name}") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=VerboseMeta): pass obj = MyClass()
Output
Creating class MyClass
Common Pitfalls
Common mistakes include forgetting to inherit from type when defining a metaclass, or not specifying the metaclass correctly in the class header. Also, overriding __init__ instead of __new__ can cause unexpected behavior because __new__ controls class creation.
python
class WrongMeta: pass # Does not inherit from type, so not a metaclass # Wrong usage - will raise TypeError # class BadClass(metaclass=WrongMeta): # pass # Correct way: class CorrectMeta(type): def __new__(cls, name, bases, dct): return super().__new__(cls, name, bases, dct) class GoodClass(metaclass=CorrectMeta): pass
Quick Reference
| Concept | Description |
|---|---|
| Metaclass | A class that creates classes, inherits from type |
| __new__ | Method to customize class creation |
| metaclass keyword | Used in class header to specify metaclass |
| Inheritance | Metaclass must inherit from type |
| Usage | class MyClass(metaclass=MyMeta): ... |
Key Takeaways
Define a metaclass by inheriting from
type and overriding __new__ to customize class creation.Use the
metaclass keyword in a class definition to apply your metaclass.Always inherit from
type when creating a metaclass to avoid errors.Override
__new__ instead of __init__ to control how classes are created.Metaclasses let you add behavior or modify classes when they are defined, not when instances are created.