Build Dynamic Classes with type
Core idea
The three-argument form type(name, bases, namespace) builds a class dynamically from its name, a tuple of base classes and a dictionary of initial attributes. It is useful when trusted configuration determines a small class shape. Functions placed in the namespace become method descriptors just as ordinary class-body functions do. The namespace is copied during normal type creation.
class BaseNotice: def display(self): return self.prefix + self.code def __init__(self, code): self.code = codeAlert = type('Alert', (BaseNotice,), {'prefix': 'AL-'})print(Alert('17').display())print(issubclass(Alert, BaseNotice), Alert.__name__)The dynamic class inherits behavior and supplies its own class attribute.
Bind a namespace function
def label(self): return self.kind.upper()attrs = {'kind': 'box', 'label': label}Box = type('Box', (), attrs)attrs['kind'] = 'bag'print(Box().label())Box.kind = 'crate'print(Box().label())Changing the original namespace mapping does not replace the class attribute. Assigning to the class itself does. The copy is shallow.
Common mistake
Use (Base,) rather than (Base) for a single base. Avoid exec or eval on untrusted configuration; selecting a known base and explicit attribute values is simpler and safer.
Practice
Create two classes from a shared base using different prefix values. Compare their names, inherited behavior and class identities.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dynamic type creation
Check your understanding of dynamic type creation.
What is printed?
C=type('Label',(),{'size':3})print(C.__name__, C().size)What is printed?
d={'x':1}; C=type('C',(),d); d['x']=7print(C.x)What must the bases argument be for ordinary three-argument type?
Which values become ordinary methods when placed in the namespace?