Functions, classes, modules, and exceptions
Practice this questionOverview
- 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
- Define small functions
- Compose them
- Inject external clients into service classes
- Import modules explicitly
- 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=[]; useNoneand create a list inside the function. - Context managers, written with
with, close files and clients even on failure.
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}")