Lesson · Advanced Object Model
Class Creation Model
75 min readClass Creation Model
A class statement executes code to build a namespace and then asks a metaclass to create the class object. Seeing classes as runtime objects prepares you for descriptors, metaclasses, and framework hooks.
Learning goals
- Trace what a
classstatement does at runtime: run the body into a namespace, hand it to a metaclass, bind the returned class object. - Name the two roles of
type: runtime class reporter and the default metaclass that creates classes. - Build a class by hand with
type(name, bases, namespace)and compare it with the equivalent class statement. - Explain why
type(Example)shows the metaclass whiletype(Example())showsExample. - Read a metaclass
__new__signature and say wheremcls,name,bases, andnamespacecome from.
Mental model
Every step is an inspectable object: the namespace is a dict while the body runs, and the class object is what the statement binds. When a class behaves unexpectedly, find the step that applied the behavior.
Mental model
read it top to bottom
class statement: body executes in a fresh namespace ↓ namespace mapping of names to objects metaclass call: type(name, bases, namespace) ↓ class object (an instance of the metaclass)
Core idea
A class is created, not declared: by the time the class statement finishes, the body has already run and a metaclass has already returned the class object. That creation step is an ordinary call, so it can be reproduced with type(name, bases, namespace) and intercepted by any subclass of type. Everything advanced about the object model starts from that insight.
Classes are objects
A class is an object like any other value: you can store it in a variable, pass it to a function, and inspect it with type. The class statement builds a namespace of names and hands it to a metaclass, and the returned object is the class itself. When a custom metaclass is in play, type(Example) reports the metaclass, which shows that the class is an instance of the thing that created it.
type
type normally returns an object's runtime class, but the type class is also the default metaclass that creates class objects. This dual role is central to Python's object model.
Dynamic class creation
Calling a metaclass such as type(name, bases, namespace) can create a class dynamically. Prefer a class statement unless the class structure truly comes from runtime data.
Class namespace
Class namespace is a mapping between names and objects used during lookup. Python creates and consults different namespaces for modules, classes, functions, and built-ins.
Class body execution
A class body executes like a block of Python code in a temporary namespace. The resulting namespace is then passed into class creation machinery.
Walkthrough
class Meta(type)subclasses the default metaclass, and its__new__(mcls, name, bases, namespace)receivesMetaasmcls, the string"Example"asname, an empty bases tuple, and a namespace holdingvalue = 42alongside the bookkeeping entries the compiler adds.super().__new__(mcls, name, bases, namespace)callstype.__new__, which performs the actual allocation and returns the class object; a metaclass__new__that forgets to return it replaces the class with whatever else it returns.- Because
class Example(metaclass=Meta)routes creation throughMeta, the print fires at definition time, before any instance exists; the final two prints then showMetafor the class object andExamplefor the instance. - Predict before running: whether
type(Example)reportstypeorMeta, and whytype(Example())reportsExamplerather thanMeta.
Experiments to try
- Print
namespaceinsideMeta.__new__and findvaluenext to the compiler-added bookkeeping entries that appear in any class statement. - Create the same class without a class statement:
Example = type("Example", (), {"value": 42}), then diff its__dict__keys against the original; the dynamic version lacks compiler-added entries like__qualname__. - Make
Meta.__new__return a plain string and printExampleafterward; the class statement binds the return value, so the name no longer refers to a class. - Give the class a second base whose metaclass is an unrelated
typesubclass and rerun; read theTypeErrorabout a metaclass conflict and name the two metaclasses it could not reconcile.
Common mistakes
- Confusing the two calling forms of
type:type(value)inspects an object's class, whiletype(name, bases, namespace)creates a new class, and the two signatures share a name but nothing else. - Assuming the class body runs per instance: it executes once, at class creation, so a print or a mutable default inside it happens once and is shared by every instance.
- Writing a metaclass
__new__without returning the class: the class statement binds the return value, so a missing return leaves the name bound toNone. - Reaching for a metaclass when a plain class attribute or a helper function would do: the metaclass affects every class built with it and composes poorly with other metaclasses.
Practice: Easy
- In the REPL, recreate
Examplefrom the worked example and printtype(Example),type(Example()), andExample.__dict__["value"]; match each result to a step in the mental model. - Rename the class to
Sampleand rerun; the printed message now sayscreating class: Sample, because the metaclass receives the name as a string. - Build
Point = type("Point", (), {"x": 0})and readPoint.x; state which parts of a class statement you had to supply by hand.
Practice: Medium
- Extend
Meta.__new__to addcreated_by = "Meta"tonamespacebefore callingsuper().__new__, then check that bothExampleand a subclass carry the attribute. - Write
make_class(name)that returnstype(name, (), {"count": 0}); create two instances, mutatecounton one, and explain why the other still reads the class attribute. - Compare editing the namespace inside
Meta.__new__with assigning an attribute after the class statement (Example.extra = 1); state at which moment each change happens and whether subclasses inherit it.
Practice: Hard
- Build an
AutoReprmetaclass whose__new__adds a__repr__that prints the class name and the instance__dict__; apply it to two classes, including one subclass, and verify the inherited behavior. - Set up a failure lab with two broken creations: one metaclass that returns a non-class, and one class whose bases have incompatible metaclasses; explain both tracebacks in terms of the creation path.
- Design a registry metaclass that records
name -> classusing anameattribute declared in the class body, and define what lookup does for an unknown name before you implement it.
Lesson checklist
- I can trace a class statement from the body executing to the class object being bound, naming each object on the way.
- I can explain both roles of
typeand demonstrate each calling form. - I can rebuild the worked example's class with
type(name, bases, namespace). - I can read a metaclass
__new__and say whatmcls,name,bases, andnamespaceeach contain.
Remember
The `class` keyword hides a creation call you can now reproduce and intercept: run the body into a namespace, call the metaclass, bind the result. With `type(...)` you can build classes by hand, and with a `type` subclass you can watch or adjust every creation that passes through it.
Interview angles
What is the main purpose of **Classes are objects**?+
A class is an object like any other value: you can store it in a variable, pass it to a function, and inspect it with type. The class statement builds a namespace of names and hands it to a metaclass, and the returned object is the class itself. When a custom metaclass is in play, type(Example) reports the metaclass, which shows that the class is an instance of the thing that created it.
What should you pay attention to when using **type**?+
type normally returns an object's runtime class, but the type class is also the default metaclass that creates class objects. This dual role is central to Python's object model.
How does **Dynamic class creation** fit into this lesson?+
Calling a metaclass such as type(name, bases, namespace) can create a class dynamically. Prefer a class statement unless the class structure truly comes from runtime data.
Why does a metaclass `__new__` that forgets to return `super().__new__(...)` break the class statement?+
The class statement binds whatever the metaclass call returns. A missing return leaves the name bound to None instead of a class object, and every later use fails as if the class were never defined.