Code Review: Refactoring Python Data Pipeline Functions
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Prompt
During a live video technical screen, your interviewer displays three compact Python routines pulled from an internal machine-learning workflow.
- Trace each routine statement by statement, explaining both its mechanics and the role it serves in the overall workflow.
- Propose three or more concrete upgrades across code clarity, execution speed, boundary-condition safety, and automated verification.
Scope & Expectations
- Line-by-line comprehension: State the high-level purpose of every routine first, then trace how data flows through its inputs, operations, and outputs.
- Correctness and boundary safety: Spot silent data corruption, brittle input parsing, overly broad error suppression, and unhandled numerical corner cases.
- Clarity and modular structure: Address identifier choices, function signatures and documentation contracts, and keeping file I/O, parameter fitting, feature transformation, and metric calculation decoupled.
- Performance and verification: Highlight opportunities to replace element-by-element Python loops with vectorized array operations, and outline targeted unit tests that verify the refactored behavior.
Step-by-step walkthrough
Frame the review: the three pipeline functions
Note: the prompt describes a live screen-share without pasting the code. Below we review three representative functions from a customer-churn pipeline (loading a CSV, scaling features, and scoring predictions) that showcase every issue the prompt hints at. The exact same review workflow applies to whatever code your interviewer shares on screen.
Suppose the raw CSV file has header
customer_id,tenure_months,monthly_spend,churned, and the interviewer shares these three functions:import numpy as np def load(p): f = open(p) rows = [] for l in f.readlines()[1:]: x = l.strip().split(",") try: rows.append([float(x[1]), float(x[2]), int(x[3])]) except: pass return np.array(rows) def prep(a): for j in range(a.shape[1] - 1): m = a[:, j].mean() s = a[:, j].std() for i in range(a.shape[0]): a[i, j] = (a[i, j] - m) / s return a def evaluate(y, p): tp = 0 fp = 0 fn = 0 for i in range(len(y)): if p[i] > 0.5 and y[i] == 1: tp += 1 if p[i] > 0.5 and y[i] == 0: fp += 1 if p[i] <= 0.5 and y[i] == 1: fn += 1 prec = tp / (tp + fp) rec = tp / (tp + fn) print("f1", 2 * prec * rec / (prec + rec))A strong live code review follows a predictable three-step rhythm so the interviewer can follow your thinking easily:
- State the purpose before criticizing. Summarize in one sentence what each function does and why the pipeline needs it, then trace its lines from top to bottom.
- Rank issues by severity. Put silent wrong answers and crashes first, hidden coupling and data leakage second, readability and testability third, and runtime speed last.
- Propose focused fixes and tests. Show clean replacement functions and name the exact unit test that proves each bug is gone.
Walk through `load`: silent row drops and brittle CSV parsing
What it does and why:
loadreads a CSV file from disk and builds a 2D numeric NumPy array holding two feature columns (tenure_months,monthly_spend) plus the binary target (churned).Going line by line exposes six concrete problems:
f = open(p)never closes the file or sets an encoding. Without awith open(..., encoding="utf-8")block, the file descriptor stays open until garbage collection runs, and the default text encoding changes across operating systems (UTF-8 on macOS/Linux vs locale encodings likecp1252on Windows).f.readlines()[1:]loads the entire file into memory at once and blindly drops row 0. It never checks that the header actually matchescustomer_id,tenure_months,monthly_spend,churned.l.strip().split(",")breaks on quoted commas. A valid CSV field containing a comma splits into extra pieces and shifts every column index after it.x[1], x[2], x[3]hard-codes column positions. If an upstream engineer inserts a new column such ascountryat index 1,loadsilently feeds the wrong numbers into the model. Also,float("nan")andfloat("inf")succeed in Python without raising an error, lettingNaNvalues sneak into the matrix.except: passswallows every error silently. A bareexceptcatches everything—evenKeyboardInterruptor a typo inside thetryblock—and drops bad rows with zero logging. Worse, if labels are exported as"1.0"and"0.0",int("1.0")raisesValueErroron every row, returning an empty 1D arrayarray([])of shape(0,)that crashes later insideprepfar from the real cause.- Features and labels are glued into one float matrix, with cryptic names. Packing
int(x[3])next to floats converts the label to1.0and forces every downstream function to remember that "the last column is the target." Single-letter names likep,f,l(which looks like1), andx, plus missing docstrings and type hints, force readers to guess the input and output contracts.
Input CSV rows: header: customer_id,tenure_months,monthly_spend,churned row 1 : c1,12,50.5,0 -> x = ["c1", "12", "50.5", "0"] -> kept: [12.0, 50.5, 0.0] row 2 : "Smith, J",3,20,1 -> x = ['"Smith', ' J"', "3", "20", "1"] -> float(' J"') fails -> SILENTLY DROPPED! row 3 : c3,6,40.0,1.0 -> int("1.0") raises ValueError -> SILENTLY DROPPED!Walk through `prep`: data leakage, in-place mutation, and slow loops
What it does and why:
prepperforms standardization (also called z-score scaling, which subtracts a column's mean and divides by its standard deviation so every feature has mean0and standard deviation1). Putting features liketenure_months(tens) andmonthly_spend(hundreds or thousands) on the same scale keeps large-magnitude columns from dominating distance-based or gradient-based models.Tracing
prepline by line reveals five serious flaws:- No
fit/transformsplit causes data leakage and serving failure. Data leakage means information from validation or test data sneaks into training. Callingprep(train)andprep(test)scales test rows using test means and standard deviations instead of training ones—and in live production, when you score one customer at a time, the standard deviation of a single row is0! Statistics must be learned once on training data and reused everywhere else. range(a.shape[1] - 1)secretly couplespreptoload. If a caller passes a feature-only matrixXwithout the label glued onto the right edge,prepsilently leaves the last real feature unscaled.a[i, j] = ...mutates the caller's input array in place. Afterscaled = prep(raw),rawhas been overwritten too, breaking any code that still needed the original values.- Integer arrays silently truncate decimal z-scores, and constant columns divide by zero. If
ahas integer dtype, writing-1.2247back intoa[i, j]chops off the decimals to-1. And if every row in a column has the same value,s = a[:, j].std()is0.0, producingNaNin float arrays (or raisingValueErrorwhen assigningNaNinto an integer array). - Nested Python loops ignore vectorization. Vectorization means writing array-level operations so NumPy runs compiled C loops instead of interpreting millions of Python loop steps. Replacing the nested
i, jloops with(X - mean) / stdis both shorter and typically 20x–50x faster on medium-sized tables.
Suppose caller passes an integer array X = [[1, 5], [2, 5], [3, 5]] (treating col 1 as label or constant feature): Column 0: mean = 2.0, std = 0.8165 True z-scores : [-1.2247, 0.0, +1.2247] Stored in int : [ -1, 0, +1] <- decimals silently truncated! If a constant feature column [5, 5, 5] is scaled: mean = 5.0, std = 0.0 -> (5 - 5) / 0.0 -> NaN (float array) or ValueError (int array)- No
Walk through `evaluate`: zero-division crashes and untestable prints
What it does and why:
evaluateturns predicted churn probabilitiespinto binary predictions at threshold0.5, counts true positives (tp), false positives (fp), and false negatives (fn), and prints the F1 score—the harmonic mean of precision and recall (2 * precision * recall / (precision + recall), a balanced average that stays near zero if either precision or recall is poor).Line by line,
evaluatehas five issues:- Crashes with
ZeroDivisionErrorwhen no positives are predicted or caught. If everyp[i] <= 0.5, thentp = 0andfp = 0, sotp / (tp + fp)divides by zero. Even whentp + fp > 0andtp + fn > 0, if the model gets every positive guess wrong (tp = 0,fp = 1,fn = 1), bothprecandrecare0.0, so2 * prec * rec / (prec + rec)divides0.0 / 0.0! print(...)instead ofreturnbreaks separation of concerns. Separation of concerns means each function handles one job. Mixing metric math with console printing means automated tests, hyperparameter searches, and experiment loggers cannot read the score back.- Hard-coded
0.5threshold ignores class imbalance. When only 5% of customers churn, most genuine churners may have calibrated probabilities between0.15and0.40; hard-coding0.5misses most of them. Makingthresholda parameter lets you tune it on validation data. - No length check on
yandp. Iterating overrange(len(y))raisesIndexErrorifpis shorter thany, and silently ignores extra elements ifpis longer! - Verbose repeated comparisons. Checking
p[i] > 0.5three separate times per row in a Python loop can be replaced by clear boolean array masks.
Normal 5-row trace at threshold 0.5: y = [1, 0, 1, 1, 0 ] p = [0.9, 0.6, 0.4, 0.8, 0.2] pred (p > 0.5): [1, 1, 0, 1, 0] -> tp = 2 (idx 0, 3), fp = 1 (idx 1), fn = 1 (idx 2) prec = 2 / (2 + 1) = 2/3, rec = 2 / (2 + 1) = 2/3, F1 = 2/3 ≈ 0.667 Crash trace when tp = 0: y = [0, 0, 1 ] p = [0.1, 0.9, 0.2] pred (p > 0.5): [0, 1, 0] -> tp = 0, fp = 1, fn = 1 prec = 0 / 1 = 0.0, rec = 0 / 1 = 0.0 -> prec + rec = 0.0 -> ZeroDivisionError!- Crashes with
Refactor `load`: explicit column names, `csv.DictReader`, and loud validation
Now we fix every issue in
loadby giving it a descriptive name, type hints, a docstring,with open(..., encoding="utf-8"), Python's standardcsv.DictReader(which handles quoted commas and looks up columns by header name), narrow exception handling that checks for finite numbers and valid{0, 1}labels, a logged count of skipped rows, and separate(X, y)return arrays:import csv import logging import math from typing import Sequence, Tuple import numpy as np logger = logging.getLogger(__name__) FEATURE_COLUMNS = ("tenure_months", "monthly_spend") LABEL_COLUMN = "churned" def load_churn_data( path: str, feature_columns: Sequence[str] = FEATURE_COLUMNS, label_column: str = LABEL_COLUMN, ) -> Tuple[np.ndarray, np.ndarray]: """Read a churn CSV into float features X of shape (n, d) and int labels y of shape (n,). Rows with missing, non-finite, or non-binary values are skipped and logged in one warning. Raises ValueError if any required column is missing or no valid rows remain. """ features = [] labels = [] skipped_rows = 0 with open(path, mode="r", encoding="utf-8", newline="") as csv_file: reader = csv.DictReader(csv_file) required = set(feature_columns) | {label_column} missing = required - set(reader.fieldnames or []) if missing: raise ValueError(f"{path}: missing required columns {sorted(missing)}") for row in reader: try: row_features = [float(row[col]) for col in feature_columns] row_label = int(row[label_column]) except (TypeError, ValueError): # TypeError occurs if a short CSV row leaves row[col] as None. skipped_rows += 1 continue if not all(math.isfinite(val) for val in row_features) or row_label not in (0, 1): skipped_rows += 1 continue features.append(row_features) labels.append(row_label) if skipped_rows > 0: logger.warning("%s: skipped %d malformed row(s)", path, skipped_rows) if not features: raise ValueError(f"{path}: no valid rows found") return np.array(features, dtype=float), np.array(labels, dtype=int)With these safeguards,
"Smith, J",3,20,1parses cleanly,"NaN"features are rejected before poisoning downstream math, and an all-"1.0"label export immediately raisesValueError: ... no valid rows foundright where the file is read.Refactor `prep` and `evaluate`: `fit`/`transform` split, vectorization, and pure metrics
Next, we decouple the pipeline so each stage has one clean contract and training statistics flow forward without leakage:
Coupled & leaky (original): CSV -> load(p) [glues X and y] -> prep(train), prep(test) [test stats leak!] -> evaluate [prints & crashes] Decoupled & leak-free (refactored): CSV -> load_churn_data -> split X, y -> fit_standardizer(X_train) -> (mean, std) | +--> standardize(X_train, mean, std) +--> standardize(X_val, mean, std) +--> standardize(X_test, mean, std) -> f1_at_threshold -> floatSplitting
prepintofit_standardizerandstandardizemirrors scikit-learn'sStandardScaler(StandardScaleris ready to use in production; writing these two helpers shows the exact mechanics clearly). Replacing constant-column standard deviations of0with1.0makes(x - mean) / 1.0 = 0.0instead ofNaN, andnp.asarray(X, dtype=float)guarantees a brand-new float array without mutating the caller's input:from typing import Sequence, Tuple import numpy as np def fit_standardizer(X_train: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Compute per-column mean and std on training features; constant columns get std = 1.0.""" X_arr = np.asarray(X_train, dtype=float) if X_arr.ndim != 2 or X_arr.shape[0] == 0: raise ValueError("X_train must be a non-empty 2D feature array") mean = X_arr.mean(axis=0) std = X_arr.std(axis=0) # Prevent division by zero: x - mean is already 0 everywhere on a constant column. std[std == 0.0] = 1.0 return mean, std def standardize(X: np.ndarray, mean: np.ndarray, std: np.ndarray) -> np.ndarray: """Return a new standardized float array without modifying X.""" X_arr = np.asarray(X, dtype=float) return (X_arr - mean) / stdFor
f1_at_threshold, notice a clean algebraic simplification whenTP > 0:precision = TP / (TP + FP), recall = TP / (TP + FN) F1 = 2 * precision * recall / (precision + recall) = 2 * TP / (2 * TP + FP + FN)Using
2 * tp / (2 * tp + fp + fn)needs just one division, and returning0.0whenevertp == 0avoids every zero-division path cleanly. Notice we keep strict>(scores > threshold) so refactoring does not silently alter boundary behavior:from typing import Sequence import numpy as np def f1_at_threshold( y_true: Sequence[int], scores: Sequence[float], threshold: float = 0.5, ) -> float: """Return positive-class F1 where score > threshold predicts 1 (returns 0.0 if TP == 0).""" y_arr = np.asarray(y_true) scores_arr = np.asarray(scores, dtype=float) if y_arr.ndim != 1 or y_arr.shape != scores_arr.shape: raise ValueError( f"Expected matching 1D shapes, got y_true={y_arr.shape} and scores={scores_arr.shape}" ) actual_pos = y_arr == 1 pred_pos = scores_arr > threshold tp = int(np.sum(pred_pos & actual_pos)) fp = int(np.sum(pred_pos & ~actual_pos)) fn = int(np.sum(~pred_pos & actual_pos)) if tp == 0: return 0.0 return 2.0 * tp / (2.0 * tp + fp + fn)Lock in every fix with targeted unit tests
Finish the review by writing small, fast unit tests where each test would have caught a real failure in the original code:
import numpy as np import pytest def test_f1_matches_hand_computed_example(): # pred_pos = [1, 1, 0, 1, 0] -> tp = 2, fp = 1, fn = 1 -> F1 = 4 / 6 = 2/3 got = f1_at_threshold([1, 0, 1, 1, 0], [0.9, 0.6, 0.4, 0.8, 0.2], threshold=0.5) assert got == pytest.approx(2.0 / 3.0) def test_f1_handles_zero_true_positives_without_crashing(): # Original evaluate() crashed with ZeroDivisionError on both inputs below. assert f1_at_threshold([0, 0, 1], [0.1, 0.9, 0.2]) == 0.0 assert f1_at_threshold([0, 0], [0.1, 0.2]) == 0.0 def test_standardize_preserves_int_input_and_constant_columns(): X_raw = np.array([[1, 5], [2, 5], [3, 5]], dtype=int) mean, std = fit_standardizer(X_raw) X_scaled = standardize(X_raw, mean, std) assert X_raw.tolist() == [[1, 5], [2, 5], [3, 5]] # input not mutated assert np.allclose(X_scaled[:, 0], [-1.22474487, 0.0, 1.22474487]) # no int truncation assert np.allclose(X_scaled[:, 1], [0.0, 0.0, 0.0]) # constant col becomes 0.0, not NaN def test_load_churn_data_parses_quoted_commas_and_skips_bad_rows(tmp_path): csv_path = tmp_path / "churn.csv" csv_path.write_text( "customer_id,tenure_months,monthly_spend,churned\n" "c1,12,50.5,0\n" '"Smith, J",3,20,1\n' "c3,NaN,30,1\n", encoding="utf-8", ) X, y = load_churn_data(str(csv_path)) assert X.tolist() == [[12.0, 50.5], [3.0, 20.0]] assert y.tolist() == [0, 1]Close your live answer with a crisp priority summary: (1) eliminate silent data loss and NaN/type bugs in
load, (2) prevent zero-division crashes and return values instead of printing inevaluate, (3) splitprepintofitandtransformwithout mutating or truncating inputs, (4) add clear names, docstrings, and type hints, and (5) vectorize column math. Ranking by real-world risk is what separates a senior review from a style checklist.
Intuition & how it works
Think of reviewing data-science pipeline code like inspecting a commercial restaurant kitchen. Before commenting on the handwriting on spice labels (variable names) or buying a faster food processor (vectorization), a good inspector checks for invisible food-safety hazards that poison dishes without an alarm—such as dropped ingredients, uncalibrated thermometers, and cross-contamination between raw and cooked stations.
Beginners often approach a code-review interview by hunting for PEP 8 style nits (l vs line, missing docstrings) or immediately rewriting every for loop into a dense one-liner. That surface-level pass misses the silent bugs that corrupt model results or crash production: except: pass quietly throwing away valid customers whose names contain commas, in-place scaling truncating decimal z-scores inside integer arrays, scaling test data with test statistics (data leakage, where information from outside the training set sneaks into model preparation), and evaluate dividing by zero whenever a threshold flags zero true positives.
Walk through three tiny rows in customer_id,tenure_months,monthly_spend,churned to see the difference:
1. Row "a,1,10,0" and row "\"Smith, J\",2,10,1", plus row "c,3,10,0": the original load splits on raw commas, silently drops "Smith, J", and glues X and y together. load_churn_data uses csv.DictReader to keep all three valid rows and returns X (3x2 float array) and y ([0, 1, 0]) separately.
2. Notice monthly_spend is [10, 10, 10] (constant, standard deviation 0) while tenure_months is integers [1, 2, 3]: the original prep divides by 0 on monthly_spend (NaN) and overwrites integer inputs. fit_standardizer replaces std == 0 with 1.0, and standardize returns a fresh float array [[-1.225, 0.0], [0.0, 0.0], [1.225, 0.0]].
3. Suppose predicted scores on [0, 1, 0] are [0.1, 0.3, 0.2] at threshold 0.5: tp = 0, fp = 0, fn = 1. The original evaluate crashes with ZeroDivisionError and only prints to stdout; f1_at_threshold safely returns 0.0 as a testable float.
Key points
- Explain before you critique. Start each function with one plain sentence stating its job in the pipeline (
loadingests raw records,prepstandardizes feature scales,evaluatescores classification quality), then read line by line. - Prioritize findings by business and engineering risk:
- Silent wrong results and crashes: bare
except: passhiding bad or quoted rows, hard-coded column indices,float("nan")sneaking through, integer array truncation, constant-column division by zero, andZeroDivisionErrorwhentp = 0. - Architecture and leakage: missing
fit/transformseparation (causing both train/test leakage offline and training/serving skew, a mismatch between how features are computed in training versus live inference), mutating caller arrays in place, couplingprepto "last column is label," and printing instead of returning. - Readability and contracts: descriptive identifiers, docstrings stating shapes and failure modes, type annotations, and named parameters instead of magic constants like
0.5. - Efficiency: vectorization (expressing column math on whole NumPy arrays so C loops replace nested Python loops).
- Silent wrong results and crashes: bare
- Fail loudly on broken contracts and log partial data issues. Catch only expected parsing exceptions (
ValueError,TypeError), verify finite numbers and valid label values, log how many rows were skipped, and raiseValueErrorif required headers are missing or zero valid rows remain. - Keep functions pure and single-purpose. Separate file I/O, statistical fitting, array transformation, metric math, and reporting so each unit can be tested with a 5-line
pytestfunction.
Common mistakes
- Stopping at style nits. Suggesting better variable names and docstrings while missing
except: pass, quoted-CSV splitting, data leakage inprep, or0 / 0inevaluateleaves every high-severity bug alive. - Replacing
except:withexcept Exception: pass. Although that stops catchingKeyboardInterrupt, bad rows still vanish with zero visibility; narrow the exception to(TypeError, ValueError)and log the count of skipped rows. - Vectorizing in place without checking array dtypes. Writing
a[:, :-1] = (a[:, :-1] - mean) / stdstill mutates the caller's array and still truncates floats ifahas integer dtype. Always allocate a float output vianp.asarray(X, dtype=float). - Silently changing boundary semantics during a refactor. Changing
p[i] > 0.5toscores >= thresholdalters predictions for exact ties at0.5; preserve>during a pure refactor and call out the choice explicitly. - Scaling training and test sets independently. Calling
fit_standardizerseparately onX_testleaks test-distribution statistics and breaks single-row real-time inference where a 1-row standard deviation is0.
Follow-up questions
- How would you adapt this workflow if the raw CSV input grows to 50 GB and no longer fits in memory?
csv.DictReaderalready streams one row at a time, so memory only blows up becauseload_churn_dataappends every row into Python lists. Instead, stream the file in fixed-size batches (for examplepandas.read_csv(..., chunksize=100_000)or converting once to a columnar Parquet file so you only read the needed columns), update column means and variances in a single pass using Welford's online algorithm (an incremental update rule that tracks running mean and sum of squared deviations without storing past rows, avoiding catastrophic cancellation—the severe loss of floating-point digits when subtracting two huge, nearly equal numbers likeE[x^2] - E[x]^2), and train with mini-batch updates such asSGDClassifier.partial_fit. - How would you structure the CSV ingestion function so unit tests can run entirely in memory without touching disk? Split file opening from row parsing: write
parse_churn_stream(lines: Iterable[str], ...)that accepts any iterable of CSV lines, and makeload_churn_data(path)a three-line wrapper that openspathand passes the file handle toparse_churn_stream. Unit tests can then pass an in-memoryio.StringIOstring directly, running faster and testing edge cases without temporary files. - When is keeping an explicit Python loop preferable to NumPy vectorization? Keep a plain loop when each step depends sequentially on the state produced by the previous step (such as a stateful cooldown rule where a customer cannot trigger a second alert within 7 days of the last alert) and no built-in cumulative NumPy operation (
np.cumsum,np.maximum.accumulate) expresses it cleanly, or whennis tiny (say 20 config items) and readability wins. If profiling proves a sequential loop is a real bottleneck, compile that loop withnumba.njitor move it into a small Cython/Rust extension rather than forcing unreadable array gymnastics.
Follow-up questions
- How would you adapt this workflow if the raw CSV input grows to 50 GB and no longer fits in memory?
- How would you structure the CSV ingestion function so unit tests can run entirely in memory without touching disk?
- When is keeping an explicit Python loop preferable to NumPy vectorization?
Similar questions
- Select Score Cutoff for Target Precision
- Structuring Screening Behavioral Answers with STAR
- Leakage-Safe SMOTE and Random Forest Pipeline
- Temporal Rare-Event Classification, Calibration, and Thresholding
- Binomial Probability and Moments for Die Rolls
- Fair-Coin and Without-Replacement Draw Probabilities
More Boston Consulting Group interview questions
- Select Score Cutoff for Target Precision Medium
- Structuring Screening Behavioral Answers with STAR Easy
- Leakage-Safe SMOTE and Random Forest Pipeline Medium Pro
- Temporal Rare-Event Classification, Calibration, and Thresholding Medium Pro
- Binomial Probability and Moments for Die Rolls Easy Pro
- Fair-Coin and Without-Replacement Draw Probabilities Easy Pro
- Bayesian Coin Updating and Stopping-Time Expectation Medium Pro
- Calibrating Downsampled Credit Risk Scores for Proactive Outreach Medium Pro
- Leakage Audits and Point-in-Time Purchase Classification Hard Pro
- Presenting Your Core Engineering Stack and Workflow Easy Pro