LESSON 18 / 215·2 min readFoundation

Functions, classes, modules, and exceptions

Must knowConcept lesson
01 Understand02 Recall03 Prepare

Words made simple

A few useful meanings before you read the explanation.

AI
Software techniques for tasks such as recognizing patterns, understanding language or generating content.
API
A way for one piece of software to ask another for data or an action. A claims API might return the current status of a claim.
State
The data describing where a workflow is now, what it already knows, and what still needs to happen.
More words from this lesson
Dependency
A library or package that your application relies on. Compatible versions help the application run as expected.

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}")
PAUSE & RECALL

Can you explain it without the notes?

Functions, classes, modules, and exceptions

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

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,…

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: Virtual environments, pip, and project structure

Adapted from 13_AI.MD · “Functions, classes, modules, and exceptions”. Examples are study fragments; framework behavior can depend on your version.