ReviseAlgo Logo

Type Hints & Annotations

Runtime Type Checking

Runtime type validation with isinstance, type guards, Pydantic, and dataclass validation — enforcing types at runtime when static checking is not enough.

Interview: Data validation — knowing when and how to validate types at runtime for API inputs and user data.

Last Updated: June 12, 2026 8 min read

While type hints are not enforced at runtime, many scenarios require runtime validation: API inputs, user data, configuration files, and deserialized data. Python provides isinstance(), type guard functions, and libraries like Pydantic for runtime type checking.

Built-in Runtime Checks

  • isinstance(obj, type) — check if object is of a type
  • issubclass(cls, parent) — check class hierarchy
  • type(obj) — exact type (no subclass matching)
  • hasattr(obj, attr) — check for attribute existence

Type Guards (Python 3.10+)

  • TypeGuard[T] — functions that narrow types for static checkers
  • Return bool, but tell mypy the type when True
  • Combines runtime checking with static type narrowing

Pydantic

  • Pydantic validates data at runtime using type annotations
  • Automatic type coercion, validation errors with detailed messages
  • Widely used in FastAPI and modern Python applications
  • BaseModel classes define schemas with type annotations

Interview Insight

Know when to use runtime validation vs static checking. API inputs always need runtime validation. Pydantic is the standard for data validation in modern Python (FastAPI, etc.).

Use Cases

API input validation — validating request bodies and query parameters

Configuration loading — ensuring config files have correct types

Data serialization — Pydantic for JSON/dict conversion with validation

Form processing — validating user-submitted form data

Database models — ensuring data integrity before persistence

Common Mistakes

Relying only on type hints for input validation — they are not enforced at runtime

Using type() instead of isinstance() — misses subclasses

Not validating external data (API, files, user input) — always validate untrusted data

Overusing isinstance checks in business logic — prefer Protocol-based design

Not using Pydantic when it would simplify validation significantly