Extend a Python Abstract Pipeline with a Concrete File Processor
Data Structure DesignModel answerLast updated
Implement a concrete subclass inside a pre-built abstract framework that streams CSV input, transforms rows to JSON, and self-registers with a CLI factory.
The Setup
You have been handed a Python codebase you did not write. It defines an abstract pipeline framework with three pieces already in place:
DataProcessor(abstract base class) — declares three abstract hooks:load(self),transform(self, record), andsave(self, records). It also owns a concreterun()method that wires those hooks together. You cannot modify this class.- A registry/factory — maps string names to processor classes. The CLI calls something like
create_processor("csv_to_json", config).run()to kick off a job. - A CLI entry point — reads a config dict, asks the registry for the right processor by name, and calls
run(). You cannot modify the CLI either.
A simplified version of the base class looks like this:
from abc import ABC, abstractmethod
class DataProcessor(ABC):
def __init__(self, config: dict):
self.config = config
def run(self):
records = (self.transform(r) for r in self.load())
self.save(records)
@abstractmethod
def load(self): ...
@abstractmethod
def transform(self, record): ...
@abstractmethod
def save(self, records): ...
Your Task
Without touching the base class, the registry implementation, or the CLI, write a concrete CsvToJsonProcessor class that:
- Streams the input CSV in fixed-size chunks rather than reading the whole file into memory.
- Transforms each row into a normalized JSON object, coercing types and enforcing any required fields listed in the config.
- Writes the output as line-delimited JSON (JSONL) to the path specified in the config.
- Handles bad rows with a two-pass retry strategy (strict parse, then a lenient fallback), logging rejected rows to a dead-letter file instead of crashing the pipeline.
- Registers itself with the factory under the name
"csv_to_json"so the CLI can find it with no other changes.
What to Provide
- The full class implementation (or a thorough outline with all key methods filled in).
- A clear explanation of how control flows from
run()through your hooks, and why the pipeline stays memory-bounded. - Your error-handling strategy: what counts as a retryable failure, what goes to the dead-letter file, and what should abort the entire job.
Config Contract
Your constructor should accept at minimum:
| Key | Type | Description |
|---|---|---|
input_path | str | Path to the source CSV |
output_path | str | Path to write the JSONL file |
chunk_size | int | Rows per chunk (default 10 000) |
required_fields | list[str] | Fields that must be non-null |
max_bad_ratio | float | Abort threshold for bad-row fraction (default 0.05) |
dead_letter_path | str | Where to write rejected rows |
Constraints and Edge Cases
- The input file may be larger than available RAM; never load it all at once.
- The header row may use inconsistent casing or surrounding whitespace — normalize keys before using them.
- A row with the wrong column count, an uncoercible value, or a missing required field is a bad row, not a crash.
- If the bad-row fraction exceeds
max_bad_ratio, raise an exception and stop — partial output is worse than no output in this context. - The output file should be written atomically (write to a temp file, then rename) so a failed run does not leave a corrupt JSONL file behind.
Hints
Hint 1
Before writing a single line of your subclass, trace what run() actually does. It builds a generator expression over load() and passes it to save(). That means load() must be a generator — if it returns a list, you break the memory-bounded guarantee without any error message to tell you why.
Hint 2
Separate two distinct failure modes: structural CSV errors (broken quoting, NUL bytes) surface inside load() when the csv reader raises csv.Error, while semantic errors (wrong type, missing required field) surface inside transform(). Handle each at the layer where it appears, and keep the generator alive in both cases.
Hint 3
Registration happens at import time. If the module containing your class is never imported, the CLI will raise a KeyError no matter how correctly you wrote the decorator. Make sure the package's __init__.py (or equivalent) imports your module, and mention this when you explain your solution.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Reading the framework before writing a single line
The first thing a strong candidate does is trace the control flow they are inheriting. run() does this:
def run(self):
records = (self.transform(r) for r in self.load())
self.save(records)
That is the Template Method pattern: the base class owns the algorithm's skeleton, and subclasses fill in the steps. Three consequences follow directly:
load()must be a generator, not a list. The generator expression(self.transform(r) for r in self.load())is pull-based —savepulls one transformed record at a time, which pulls onetransform, which pulls one row fromload. Memory usage is bounded by chunk size, not file size.transform()must handle a single record and return somethingsavecan serialize, orNoneto signal rejection.save()must consume the iterable lazily. Callinglist()on it would negate all the streaming work upstream.
Hook responsibilities
| Hook | Input | Output | Key concern |
|---|---|---|---|
load | (none, reads input_path) | generator of raw dicts | Structural CSV errors; blank lines; column-count mismatches |
transform | one raw dict | normalized dict or None | Type coercion; required-field validation; two-pass retry |
save | lazy iterable of dicts | JSONL file on disk | Atomic write; flush on completion |
Error handling strategy
There are two distinct failure classes, and conflating them is a common mistake.
Structural errors come from csv.reader itself — broken quoting, NUL bytes, field-size overflow. These raise csv.Error inside load. Catch them per row, log the line number, and continue iterating. Do not let a single malformed row kill the generator.
Semantic errors come from transform — a missing required field, a value that cannot be coerced to the expected type. Here "retry" means try a different parsing strategy, not repeat the same deterministic operation. The two passes are:
- Strict: coerce each value to its target type; reject if any required field is absent or
None. - Lenient: strip stray whitespace and quotes, fall back to string types for non-critical fields, and try again.
If both passes fail, the row goes to the dead-letter file with its line number and the error message. Exponential backoff belongs on I/O operations, not on pure in-memory parsing.
Add a circuit breaker: if bad / seen > max_bad_ratio, raise TooManyBadRows and abort. A file that is 20 % garbage usually means the wrong delimiter or schema was passed in — silently emitting 80 % of it is a worse outcome than failing loudly.
Implementation
import csv
import json
import logging
import os
import tempfile
from typing import Iterator, Optional
from framework.base import DataProcessor
from framework.registry import register_processor
log = logging.getLogger(__name__)
class TooManyBadRows(RuntimeError):
pass
@register_processor("csv_to_json")
class CsvToJsonProcessor(DataProcessor):
"""Streams a CSV file and writes normalized JSONL output."""
def __init__(self, config: dict):
super().__init__(config)
self.input_path = config["input_path"]
self.output_path = config["output_path"]
self.chunk_size = int(config.get("chunk_size", 10_000))
self.required = [self._norm_key(f) for f in config.get("required_fields", [])]
self.max_bad_ratio = float(config.get("max_bad_ratio", 0.05))
self.dead_letter_path = config.get("dead_letter_path", self.output_path + ".bad")
self._seen = 0
self._bad = 0
# ------------------------------------------------------------------ load
def load(self) -> Iterator[dict]:
with open(self.input_path, newline="", encoding="utf-8-sig") as f:
reader = csv.reader(f)
header = next(reader, None)
if header is None:
return
keys = [self._norm_key(h) for h in header]
chunk = []
for row in self._safe_iter(reader):
if row is None: # structural error flagged by _safe_iter
continue
if not any(c.strip() for c in row):
continue # skip blank lines
if len(row) != len(keys):
yield {"_line": reader.line_num, "_raw": row,
"_error": f"expected {len(keys)} cols, got {len(row)}"}
else:
yield {"_line": reader.line_num, **dict(zip(keys, row))}
def _safe_iter(self, reader):
"""Wrap csv iteration so csv.Error does not kill the generator."""
while True:
try:
yield next(reader)
except StopIteration:
return
except csv.Error as e:
self._seen += 1
self._record_bad(reader.line_num, None, f"csv error: {e}")
yield None
# -------------------------------------------------------------- transform
def transform(self, record: dict) -> Optional[dict]:
self._seen += 1
line = record.pop("_line")
raw = record.pop("_raw", list(record.values()))
if "_error" in record:
return self._record_bad(line, raw, record["_error"])
for strategy in (self._strict, self._lenient):
try:
return strategy(dict(record))
except (ValueError, KeyError) as exc:
last_exc = exc
return self._record_bad(line, raw, str(last_exc))
def _strict(self, rec: dict) -> dict:
out = {k: self._coerce(v) for k, v in rec.items()}
missing = [k for k in self.required if not out.get(k)]
if missing:
raise KeyError(f"missing required fields: {missing}")
return out
def _lenient(self, rec: dict) -> dict:
out = {}
for k, v in rec.items():
v = v.strip().strip('"\'')
try:
out[k] = self._coerce(v)
except ValueError:
out[k] = v # fall back to raw string
missing = [k for k in self.required if not out.get(k)]
if missing:
raise KeyError(f"still missing after lenient pass: {missing}")
return out
# ------------------------------------------------------------------ save
def save(self, records):
dir_ = os.path.dirname(self.output_path) or "."
with tempfile.NamedTemporaryFile("w", dir=dir_, delete=False,
suffix=".tmp", encoding="utf-8") as tmp:
try:
for rec in records: # pulls the whole lazy pipeline
if rec is not None:
tmp.write(json.dumps(rec, ensure_ascii=False) + "\n")
except TooManyBadRows:
os.unlink(tmp.name)
raise
os.replace(tmp.name, self.output_path) # atomic rename
log.info("wrote %s (%d bad / %d total)", self.output_path,
self._bad, self._seen)
# ---------------------------------------------------------------- helpers
def _record_bad(self, line, raw, reason) -> None:
self._bad += 1
if self._seen and (self._bad / self._seen) > self.max_bad_ratio:
raise TooManyBadRows(
f"{self._bad}/{self._seen} rows bad, exceeds {self.max_bad_ratio:.0%}"
)
log.warning("line %d rejected: %s", line, reason)
with open(self.dead_letter_path, "a", encoding="utf-8") as f:
f.write(json.dumps({"line": line, "raw": raw, "reason": reason}) + "\n")
return None
@staticmethod
def _norm_key(s: str) -> str:
return s.strip().lower().replace(" ", "_")
@staticmethod
def _coerce(v: str):
v = v.strip()
if v == "":
return None
for cast in (int, float):
try:
return cast(v)
except ValueError:
pass
if v.lower() in ("true", "false"):
return v.lower() == "true"
return v
Common mistakes to avoid
- Returning a list from
load— silently defeats streaming; the whole file lands in memory beforetransformsees row one. - Retrying with identical logic — a deterministic parse will fail identically every time. Retry means a different strategy, not a loop counter.
- Forgetting to import the module — the
@register_processordecorator runs at import time. If the file is never imported, the registry has no entry and the CLI raisesKeyError. Wire it into the package's__init__.py. - Writing output in-place — a crash mid-write leaves a corrupt JSONL file. The temp-file-then-rename pattern makes the output appear atomically or not at all.
Complexity
- Time: O(n) in the number of rows — one pass, constant work per row.
- Memory: O(chunk_size) — only one chunk is live at any moment between
loadandsave.