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.

  1. Trace each routine statement by statement, explaining both its mechanics and the role it serves in the overall workflow.
  2. 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

  1. 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:

    1. 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.
    2. 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.
    3. Propose focused fixes and tests. Show clean replacement functions and name the exact unit test that proves each bug is gone.
  2. Walk through `load`: silent row drops and brittle CSV parsing

    What it does and why: load reads 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 a with 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 like cp1252 on Windows).
    • f.readlines()[1:] loads the entire file into memory at once and blindly drops row 0. It never checks that the header actually matches customer_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 as country at index 1, load silently feeds the wrong numbers into the model. Also, float("nan") and float("inf") succeed in Python without raising an error, letting NaN values sneak into the matrix.
    • except: pass swallows every error silently. A bare except catches everything—even KeyboardInterrupt or a typo inside the try block—and drops bad rows with zero logging. Worse, if labels are exported as "1.0" and "0.0", int("1.0") raises ValueError on every row, returning an empty 1D array array([]) of shape (0,) that crashes later inside prep far 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 to 1.0 and forces every downstream function to remember that "the last column is the target." Single-letter names like p, f, l (which looks like 1), and x, 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!
    
  3. Walk through `prep`: data leakage, in-place mutation, and slow loops

    What it does and why: prep performs standardization (also called z-score scaling, which subtracts a column's mean and divides by its standard deviation so every feature has mean 0 and standard deviation 1). Putting features like tenure_months (tens) and monthly_spend (hundreds or thousands) on the same scale keeps large-magnitude columns from dominating distance-based or gradient-based models.

    Tracing prep line by line reveals five serious flaws:

    • No fit / transform split causes data leakage and serving failure. Data leakage means information from validation or test data sneaks into training. Calling prep(train) and prep(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 is 0! Statistics must be learned once on training data and reused everywhere else.
    • range(a.shape[1] - 1) secretly couples prep to load. If a caller passes a feature-only matrix X without the label glued onto the right edge, prep silently leaves the last real feature unscaled.
    • a[i, j] = ... mutates the caller's input array in place. After scaled = prep(raw), raw has 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 a has integer dtype, writing -1.2247 back into a[i, j] chops off the decimals to -1. And if every row in a column has the same value, s = a[:, j].std() is 0.0, producing NaN in float arrays (or raising ValueError when assigning NaN into 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, j loops with (X - mean) / std is 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)
    
  4. Walk through `evaluate`: zero-division crashes and untestable prints

    What it does and why: evaluate turns predicted churn probabilities p into binary predictions at threshold 0.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, evaluate has five issues:

    • Crashes with ZeroDivisionError when no positives are predicted or caught. If every p[i] <= 0.5, then tp = 0 and fp = 0, so tp / (tp + fp) divides by zero. Even when tp + fp > 0 and tp + fn > 0, if the model gets every positive guess wrong (tp = 0, fp = 1, fn = 1), both prec and rec are 0.0, so 2 * prec * rec / (prec + rec) divides 0.0 / 0.0!
    • print(...) instead of return breaks 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.5 threshold ignores class imbalance. When only 5% of customers churn, most genuine churners may have calibrated probabilities between 0.15 and 0.40; hard-coding 0.5 misses most of them. Making threshold a parameter lets you tune it on validation data.
    • No length check on y and p. Iterating over range(len(y)) raises IndexError if p is shorter than y, and silently ignores extra elements if p is longer!
    • Verbose repeated comparisons. Checking p[i] > 0.5 three 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!
    
  5. Refactor `load`: explicit column names, `csv.DictReader`, and loud validation

    Now we fix every issue in load by giving it a descriptive name, type hints, a docstring, with open(..., encoding="utf-8"), Python's standard csv.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,1 parses cleanly, "NaN" features are rejected before poisoning downstream math, and an all-"1.0" label export immediately raises ValueError: ... no valid rows found right where the file is read.

  6. 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 -> float
    

    Splitting prep into fit_standardizer and standardize mirrors scikit-learn's StandardScaler (StandardScaler is ready to use in production; writing these two helpers shows the exact mechanics clearly). Replacing constant-column standard deviations of 0 with 1.0 makes (x - mean) / 1.0 = 0.0 instead of NaN, and np.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) / std
    

    For f1_at_threshold, notice a clean algebraic simplification when TP > 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 returning 0.0 whenever tp == 0 avoids 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)
    
  7. 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 in evaluate, (3) split prep into fit and transform without 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 (load ingests raw records, prep standardizes feature scales, evaluate scores classification quality), then read line by line.
  • Prioritize findings by business and engineering risk:
    1. Silent wrong results and crashes: bare except: pass hiding bad or quoted rows, hard-coded column indices, float("nan") sneaking through, integer array truncation, constant-column division by zero, and ZeroDivisionError when tp = 0.
    2. Architecture and leakage: missing fit / transform separation (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, coupling prep to "last column is label," and printing instead of returning.
    3. Readability and contracts: descriptive identifiers, docstrings stating shapes and failure modes, type annotations, and named parameters instead of magic constants like 0.5.
    4. Efficiency: vectorization (expressing column math on whole NumPy arrays so C loops replace nested Python loops).
  • 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 raise ValueError if 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 pytest function.

Common mistakes

  • Stopping at style nits. Suggesting better variable names and docstrings while missing except: pass, quoted-CSV splitting, data leakage in prep, or 0 / 0 in evaluate leaves every high-severity bug alive.
  • Replacing except: with except Exception: pass. Although that stops catching KeyboardInterrupt, 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) / std still mutates the caller's array and still truncates floats if a has integer dtype. Always allocate a float output via np.asarray(X, dtype=float).
  • Silently changing boundary semantics during a refactor. Changing p[i] > 0.5 to scores >= threshold alters predictions for exact ties at 0.5; preserve > during a pure refactor and call out the choice explicitly.
  • Scaling training and test sets independently. Calling fit_standardizer separately on X_test leaks test-distribution statistics and breaks single-row real-time inference where a 1-row standard deviation is 0.

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.DictReader already streams one row at a time, so memory only blows up because load_churn_data appends every row into Python lists. Instead, stream the file in fixed-size batches (for example pandas.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 like E[x^2] - E[x]^2), and train with mini-batch updates such as SGDClassifier.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 make load_churn_data(path) a three-line wrapper that opens path and passes the file handle to parse_churn_stream. Unit tests can then pass an in-memory io.StringIO string 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 when n is tiny (say 20 config items) and readability wins. If profiling proves a sequential loop is a real bottleneck, compile that loop with numba.njit or move it into a small Cython/Rust extension rather than forcing unreadable array gymnastics.

Follow-up questions

Similar questions

More Boston Consulting Group interview questions

All 23 Boston Consulting Group questions →