InterviewHubPRO
Section Overview
Q21

Question 21 of 65

Part 2: Python Core Language, Internals & Runtime (6 - 25)

32%
Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)

Dataclasses vs NamedTuple vs Pydantic:

In Simple Words:

  • dataclass: Built-in; automatically generates __init__, __repr__, and __eq__.
  • NamedTuple: Immutable tuple subclass; lightweight with named fields.
  • Pydantic: Full data parsing and runtime validation for APIs with JSON coercion.
python
from dataclasses import dataclass
from pydantic import BaseModel

@dataclass
class UserDataClass:
    name: str
    age: int

class UserPydantic(BaseModel):
    name: str
    age: int # Coerces "25" to 25 and validates at runtime