Phase 8 of 25 · Topic 8.1

Understanding type as the Default Metaclass

1Concept

In Python, classes are themselves objects created by the default metaclass `type`. Calling `type(name, bases, dict)` dynamically allocates and returns a new class at runtime without the `class` keyword.

2Architecture Diagram

type('ClassName', (Base,), {'attribute': value}) ---> Dynamically creates class in memory

3Code Example

Python 3.12
# Dynamic runtime class creation
def say_hello(self):
    return f"Hello from dynamic {self.__class__.__name__}"

DynamicService = type(
    "DynamicService",
    (object,),
    {"version": "2.1", "greet": say_hello}
)

instance = DynamicService()
print(f"Class Name: {instance.__class__.__name__}")
print(f"Version:    {instance.version}")
print(instance.greet())

4Expected Output

Class Name: DynamicService
Version:    2.1
Hello from dynamic DynamicService

5Key Takeaways

  • `type` is the metaclass that creates classes, and an instance of itself.
  • `isinstance(ClassName, type)` evaluates to True for standard Python classes.
  • Dynamic class generation is the foundation of ORMs (SQLAlchemy, Django) and serialization libraries.