Choose Class Decorators or Metaclass Hooks
Core idea
Choose the least invasive class customization mechanism. A class decorator receives the created class and can modify or replace it for that definition. A base init_subclass hook applies an inherited policy to future subclasses. A metaclass can customize class namespace preparation, construction and calls to the class. Decorators run after class creation hooks, so they cannot retroactively change how the original body was executed.
def exportable(cls): cls.exportable = True return cls@exportableclass Report: passclass Draft: passprint(Report.exportable, hasattr(Draft, 'exportable'))class DetailedReport(Report): passprint(DetailedReport.exportable)Only Report is directly decorated. Its added attribute can still be inherited; the decorator is not automatically executed again for the subclass.
Compare creation hook order
def mark(cls): print('decorate', cls.__name__) return clsclass Meta(type): def __new__(mcls, name, bases, ns): print('create', name) return super().__new__(mcls, name, bases, ns)class Base(metaclass=Meta): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) print('subclass', cls.__name__)@markclass Report(Base): passThe metaclass creates Report through type.new, which invokes the base hook; only afterward does the decorator receive the class.
Common mistake
Do not choose a metaclass solely to add a marker attribute. Also avoid decorators that return a different class without documenting identity changes; registration hooks may already have seen the original.
Practice
Design a policy for an optional export label and another for mandatory subclass registration. Implement each with the simplest appropriate hook and explain why a custom metaclass is unnecessary.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Class decorators versus metaclasses
Check your understanding of class decorators versus metaclasses.
What is printed?
def mark(cls): print(cls.__name__); return cls@markclass A: passclass B(A): passWhat is printed?
def change(cls): cls.x=7; return cls@changeclass A: x=1print(A.x)Which mechanism best fits a one-off optional class marker?
Which mechanism can supply a custom class-body namespace before execution?