Sub topic 2
Creating classes with type()
This chapter assumes you can define classes, methods and inheritance, and that you know how to call a function with positional and keyword arguments. It also assumes you have seen that every class is an object and that type(obj) returns the class of obj. Here you will use the three-argument form of type() to build classes at runtime and see where it differs from a class statement.
Two jobs for one name
The name type does two jobs, depending on how many arguments you pass.
| Call | What it does |
|---|---|
| `type(obj)` | Returns the class of `obj`. |
| `type(name, bases, namespace)` | Creates and returns a new class. |
The one-argument form is the one you use most often. The three-argument form is the one that creates classes, and it is what Python itself uses to build every class you write.
class Dog:
pass
print(type(Dog())) # <class '__main__.Dog'>
print(type(Dog)) # <class 'type'>
print(type(type)) # <class 'type'>Dog is an object, and its class is type. That makes type the default metaclass, meaning the class whose instances are classes. Calling type(...) with three arguments is therefore the same operation as calling any class to get an instance. The instance you get back happens to be another class.
The three arguments
The three-argument call takes these arguments:
name: a string that becomes the class's__name__.bases: a tuple of parent classes. An empty tuple means the only base isobject.namespace: a dict that becomes the class attributes, including methods.
Point = type('Point', (), {'x': 0, 'describe': lambda self: f'Point at x={self.x}'})
p = Point()
print(type(Point)) # <class 'type'>
print(p.describe()) # Point at x=0The lambda in the dict is an ordinary function. When you look it up through an instance, Python binds it as a method, exactly as it does for a function defined in a class body. Nothing about "method" is special at creation time. A method is a function stored in a class namespace.
What the new class gets for free
type() fills in the metadata that a class statement would also set.
def describe(self):
return f'Point at x={self.x}'
Point = type('Point', (), {'x': 0, 'describe': describe})
print(Point.__name__) # Point
print(Point.__qualname__) # Point
print(Point.__module__) # __main__
print(Point.__bases__) # (<class 'object'>,)
print(Point.x) # 0__module__ comes from the module that called type(). If your factory function lives in factories.py, classes it builds get factories as their module unless you put '__module__' in the namespace yourself. This matters for pickle, which finds a class by importing its module and looking up its qualified name. A class built dynamically is only picklable if that lookup finds the same class.
The namespace is copied
type() copies the namespace dict into the class. Changing your original dict afterward has no effect on the class.
ns = {'x': 1}
K = type('K', (), ns)
ns['x'] = 2
print(K.x) # 1
K.x = 3 # assigning on the class itself does change it
print(K.x) # 3The class's own __dict__ is a read-only mappingproxy. You change attributes by assigning on the class, not by editing __dict__. You can also add methods after creation with Point.scale = some_function, which is a common way to extend a class at runtime.
Inheritance with a tuple of bases
The bases argument must be a tuple. The most common mistake is writing a single base in parentheses without the trailing comma.
class Animal:
def speak(self):
return '...'
Dog = type('Dog', (Animal,), {'speak': lambda self: 'Woof'})
Puppy = type('Puppy', (Dog,), {})
print(Dog().speak()) # Woof
print(Puppy().speak()) # Woof
print(issubclass(Puppy, Animal)) # True
print([c.__name__ for c in Puppy.__mro__]) # ['Puppy', 'Dog', 'Animal', 'object']type('Dog', (Animal), {}) passes the class Animal itself, not a tuple, and raises TypeError. The parentheses alone do not make a tuple; the comma does.
Method resolution order (MRO) works the same as for a class statement, including multiple bases and the C3 linearization rules. If your bases cannot be linearized consistently, type() raises TypeError, as it would for a class line.
Building classes from data
The practical use of type() is generating classes whose shape is known only at runtime, for example from a schema, a config file or a database table. A factory function closes over the data and returns a new class.
def make_record(name, fields):
fields = tuple(fields)
def __init__(self, *args):
if len(args) != len(fields):
raise TypeError(
f'{name} expects {len(fields)} arguments, got {len(args)}'
)
for field, value in zip(fields, args):
setattr(self, field, value)
def __repr__(self):
pairs = ', '.join(f'{f}={getattr(self, f)!r}' for f in fields)
return f'{name}({pairs})'
return type(name, (), {
'__init__': __init__,
'__repr__': __repr__,
'__slots__': fields,
'__module__': __name__,
})
Person = make_record('Person', ['name', 'age'])
ada = Person('Ada', 36)
print(ada) # Person(name='Ada', age=36)
try:
Person('Grace')
except TypeError as exc:
print(exc) # Person expects 2 arguments, got 1Three details are worth noting:
- Special methods such as
__init__and__repr__are looked up on the class, so putting them in the namespace is enough. __slots__in the namespace works. Python reads it while building the class, which is why it must be in the dict passed totype()and cannot be added later.'__module__': __name__sets the module explicitly, so the result does not depend on who called the factory.
The standard library uses this technique. collections.namedtuple and dataclasses.make_dataclass both build classes this way internally.
What a class statement adds that type() does not
A class statement is not just syntax for the type() call. Before the call, Python runs the class body to build the namespace. It also performs steps that a bare type() call skips. The next chapter walks through those steps in order, but one difference already affects dynamic classes.
Zero-argument super() relies on a hidden __class__ cell that the compiler creates for functions defined inside a class body. A function defined outside the class and passed in through the namespace has no such cell.
class Base:
def hello(self):
return 'base'
def hello(self):
return super().hello() + ' child'
Child = type('Child', (Base,), {'hello': hello})
try:
Child().hello()
except RuntimeError as exc:
print(exc) # super(): __class__ cell not foundThe fix is to use the explicit two-argument form, which looks up Child in the module globals when the method runs.
def hello(self):
return super(Child, self).hello() + ' child'
Child = type('Child', (Base,), {'hello': hello})
print(Child().hello()) # base childWhere type() falls short: types.new_class
Calling type() directly always starts from type itself. If any of your bases uses a custom metaclass, the resulting class still ends up with that more specific metaclass, but the class-creation protocol is only partly followed. In particular, type() does not call the metaclass's __prepare__ method, which supplies the namespace object for the class body. You will meet __prepare__ in a later chapter.
The types module provides types.new_class, which follows the full protocol that a class statement uses. It chooses the correct metaclass from the bases, calls __prepare__, runs a body function that fills the namespace, and then creates the class.
import types
def fill(ns):
ns['x'] = 0
ns['describe'] = lambda self: f'Point at x={self.x}'
Point = types.new_class('Point', (), {}, fill)
print(Point().describe()) # Point at x=0The third argument is a dict of class keyword arguments, here empty. The fourth is a callable that receives the namespace and populates it. For plain classes with no custom metaclass, type() and types.new_class give the same result. Prefer types.new_class when your bases might come from code you do not control.
How the pieces fit together
The diagram shows that a class statement and a direct type() call meet at the same step.
Common errors
- Forgetting the tuple comma.
(Animal)is not a tuple. Write(Animal,). - Passing a non-string name. The first argument must be a
str. - Mutating the namespace after creation. Changes to your dict do not reach the class. Assign on the class instead.
- Relying on zero-argument
super(). It fails for functions defined outside a class body, as shown above. - Unpicklable dynamic classes. If pickle cannot find the class by its module and qualified name, pickling instances fails. Assign the result to a module-level name that matches the class name.
- Building classes in a hot path. Class creation is much slower than creating an instance, and each class stays in memory until nothing references it. Create dynamic classes once and reuse them.
Exercises
Exercise
Write a call to type() that creates a class named Counter with a class attribute count set to 0 and a method increment that adds 1 to self.count and returns the new value. What does Counter().increment() return, and what is Counter.count afterward?
Show answer
Define def increment(self): self.count += 1; return self.count, then Counter = type('Counter', (), {'count': 0, 'increment': increment}). Counter().increment() returns 1. Counter.count is still 0, because self.count += 1 reads the class attribute and then stores the result as a new attribute on the instance, which leaves the class attribute unchanged.
Exercise
A teammate writes Dog = type('Dog', (Animal), {'speak': lambda self: 'Woof'}) and gets a TypeError. What is wrong, and how do you fix it?
Show answer
(Animal) is just Animal in parentheses, not a tuple, so the bases argument is not a tuple. Add a trailing comma: type('Dog', (Animal,), {'speak': lambda self: 'Woof'}).
Exercise
You attach a function containing zero-argument super() to a class built with type(). Calling it raises RuntimeError. Why does this happen, and give two ways to avoid it.
Show answer
The compiler creates the _class_ cell only for functions defined inside a class body, so a function defined outside has no cell for super() to read. Either call super(ClassName, self) explicitly, or define the class with a class statement so the compiler creates the cell.