Sub topic 2
Creating classes with type()
This chapter assumes you can write classes with inheritance in Python and you know what __init__ and instance attributes are. The previous chapter showed that a class is an object. Here you build one by calling type directly.
Two jobs for type
type does two things, depending on how many arguments you pass:
type(obj)with one argument returns the class ofobj.type(name, bases, namespace)with three arguments creates and returns a new class.
The three arguments are:
| Argument | Type | Meaning |
|---|---|---|
| `name` | `str` | Becomes the class's `__name__` |
| `bases` | `tuple` of classes | The parent classes, in order |
| `namespace` | `dict` | Attributes and methods of the class |
A first dynamic class
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 empty tuple means the only base is object. The dict supplies a class attribute x and a method describe. A method in the namespace is an ordinary function whose first parameter is self. It becomes a method when it is looked up on an instance.
type(Point) is type, which shows that Point is an instance of type. A normal class statement produces the same result.
Bases, methods and inheritance
Here is a larger example. It builds a parent and a child class from plain functions.
def init(self, name):
self.name = name
def greet(self):
return f'{self.name} says {self.sound}'
Animal = type('Animal', (), {'sound': '...', '__init__': init, 'greet': greet})
Dog = type('Dog', (Animal,), {'sound': 'woof'})
d = Dog('Rex')
print(d.greet()) # Rex says woof
print(Dog.__name__) # Dog
print(Dog.__bases__) # (<class '__main__.Animal'>,)
print(issubclass(Dog, Animal)) # TrueDog supplies only sound. It inherits __init__ and greet from Animal, exactly as it would with a class Dog(Animal): statement.
The class statement is not the same as the name
type returns the class. It does not bind a variable. The string you pass as name only sets __name__, so the two can differ:
Thing = type('Widget', (), {})
print(Thing.__name__) # Widget
print(Thing) # <class '__main__.Widget'>Normally you assign the result to a variable with the same name as the string. When the two differ, error messages and repr output show the string, not the variable. That can confuse you while debugging.
Common errors
- Bases must be a tuple. A single base needs a trailing comma:
(Animal,). Writing(Animal)passes the class itself, andtyperaises aTypeError. - The namespace is copied.
typecopies the dict into the class, so changing your dict afterwards does not change the class. - Duplicate method names vanish silently in a dict. A dict literal keeps only the last value for a repeated key, with no warning. A later chapter on
__prepare__shows how to catch this in class bodies. __module__comes from the caller.typetakes it from the module where you called it. If you create classes inside a helper library, they report the library as their module unless you put'__module__'in the namespace. This matters forpickle, which finds classes by module and name.
When this is useful
Most code should use a class statement because it is clearer. Calling type directly fits cases where the shape of the class is only known at runtime. For example, you might build one class per table in a database schema, or one per entry in a configuration file.
def make_record(name, fields):
def init(self, **values):
for field in fields:
setattr(self, field, values[field])
return type(name, (), {'__init__': init, '__slots__': tuple(fields)})
User = make_record('User', ['id', 'email'])
u = User(id=1, email='[email protected]')
print(u.id, u.email) # 1 [email protected]The next chapter shows what Python does when it runs a class statement. That process ends in a call like the ones you wrote here.
Exercise
Using type(), create a class named Counter with one base, Base (already defined as class Base: pass). Counter must have a class attribute count equal to 0 and a method bump that adds 1 to self.count and returns it. What does the call look like, and why does type('Counter', (Base), {}) fail?
Show answer
def bump(self):
self.count += 1
return self.count
Counter = type('Counter', (Base,), {'count': 0, 'bump': bump})
(Base) is only the class Base in parentheses, not a tuple, so type receives a class where it needs a tuple of bases and raises a TypeError. A one-element tuple needs a trailing comma: (Base,). Calling Counter().bump() returns 1. The instance gets its own count attribute, and the class attribute stays 0.