QA
Senior LevelPython

How do you dynamically generate ORM models or API serializers at runtime using the 3-argument type(name, bases, dict) constructor?

❓ Interview Prompt: Explain Metaclasses, dynamic class creation using `type('Name', (Bases,), {attributes})`, and runtime code generation.

In Python, classes are instances of the metaclass 'type'. You can dynamically instantiate new classes at runtime using the 3-argument 'type(name, bases, dict)' constructor:

Parameters:

1
'name': String name of the new class.
2
'bases': Tuple of parent classes to inherit from.
3
'dict': Dictionary mapping class attribute names to values and functions.

Code Implementation Example

python
# Dynamically construct a new class at runtime!
DynamicUserModel = type(
    'DynamicUserModel',
    (object,), # Base classes tuple
    {
        'role': 'ADMIN',
        'get_role': lambda self: self.role
    }
)

instance = DynamicUserModel()
print(instance.get_role()) # 'ADMIN'
💡Dynamically constructing classes at runtime using the 3-argument type() constructor.
🎯 Interview Key Takeaway

Use the 3-argument type() constructor to dynamically generate classes at runtime for ORM schemas and dynamic serializers.

#metaclass#type()#Dynamic Classes#Metaprogramming#Senior
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?