AI EngineeringInterview preparation
Foundation·Concept·2 min read

Functions, classes, modules, and exceptions

Practice this question

Overview

  • Functions package operations; classes group state and behavior; modules are importable Python files or packages.
  • Exceptions represent errors that interrupt normal control flow until handled.
  • These serve the same broad purposes as functions, classes, imports, and errors in TypeScript.

Why this matters

AI pipelines still need ordinary maintainable code with clear boundaries and failure handling.

An everyday example

Separate employees handle parsing, validation, and storage; a failed task is escalated to the right person.

A technical example

def normalize_text(text: str) -> str: return " ".join(text.split()) is a reusable cleanup function.

How it works

  1. Define small functions
  2. Compose them
  3. Inject external clients into service classes
  4. Import modules explicitly
  5. Catch expected errors at service boundaries.

Architecture and flow

API module → ingestion service → parser function → storage adapter; error → classified response/retry.

The insurance assistant example

PolicyParser returns paragraphs; unreadable PDFs produce a parsing error and a review task rather than an empty successful document.

When to use it

Use functions by default and classes for persistent dependencies or coherent state.

When to avoid it

Avoid elaborate inheritance for three straightforward steps and avoid except Exception: pass.

Interview answer

“I use small typed functions, explicit dependency injection, and specific exception handling so AI pipeline failures are observable and recoverable.”

Benefits, trade-offs, and production considerations

  • Avoid mutable default arguments such as items=[]; use None and create a list inside the function.
  • Context managers, written with with, close files and clients even on failure.
Python
class UnsupportedDocument(ValueError):
    pass

class PolicyParser:
    def parse(self, text: str) -> list[str]:
        if not text.strip():
            raise UnsupportedDocument("No readable policy text")
        return [part.strip() for part in text.split("\n\n") if part.strip()]

try:
    paragraphs = PolicyParser().parse("Coverage\n\nExclusions")
except UnsupportedDocument as error:
    print(f"Send to document review: {error}")
Adapted from 13_AI.MD · “Functions, classes, modules, and exceptions”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.