Debugging & Reading Errors
A traceback identifies the operation that failed and the calls that reached it. Read the exception first, then inspect the last frame in your own code. The value can become invalid before that frame, so follow its path back to the input.
Save the Python blocks below in debugging_examples.py, in page order. Use the uv project setup and add NumPy and pandas with uv add numpy pandas. Run the file with uv run python debugging_examples.py. Each deliberate failure is caught so the next example can run.
Read the exception and your own frames
Section titled “Read the exception and your own frames”These counts contain numeric text, which is different from numeric data. The example requests object dtype explicitly so that the failure does not depend on a pandas default.
import iofrom pathlib import Pathfrom tempfile import TemporaryDirectoryimport tracebackimport warnings
import numpy as npimport pandas as pd
def divide_by_total(counts: pd.Series, total: float) -> pd.Series: """Divide a series by its library total.
Args: counts: Numeric counts for one sample. total: Sum of the sample's counts.
Returns: Fractions of the library total. """ return counts / total
def cpm_unchecked(counts: pd.Series) -> pd.Series: """Calculate CPM without checking the input dtype.
Args: counts: Counts for one sample.
Returns: Counts per million for a valid numeric input. """ return divide_by_total(counts, counts.sum()) * 1e6
text_counts = pd.Series(["120", "455", "89"], dtype=object)try: cpm_unchecked(text_counts)except TypeError as error: print(f"{type(error).__name__}: {error}") for frame in traceback.extract_tb(error.__traceback__): if frame.filename == __file__: print(f"{frame.name}: {frame.line}")TypeError: unsupported operand type(s) for /: 'str' and 'str'<module>: cpm_unchecked(text_counts)cpm_unchecked: return divide_by_total(counts, counts.sum()) * 1e6divide_by_total: return counts / totalThe exception identifies the unsupported division. The displayed frames show the path through cpm_unchecked and divide_by_total. The input creation line is not a call frame, but that line supplies the strings that reach the division.
For this input, explicit conversion solves the type problem. errors="raise" also rejects a value such as "unknown" instead of replacing it silently.
numeric_counts = pd.to_numeric(text_counts, errors="raise")scaled_counts = cpm_unchecked(numeric_counts)print("Numeric dtype:", numeric_counts.dtype)print("CPM:", np.round(scaled_counts.to_numpy(), 3))print("CPM total:", float(scaled_counts.sum()))Numeric dtype: int64CPM: [180722.892 685240.964 134036.145]CPM total: 999999.9999999999CPM divides each count by the sum of counts for that sample. The number of genes is not the denominator. The small difference from one million comes from floating-point arithmetic. Input conversion alone does not check missing counts or a zero library total; the validation example below does.
Inspect the values behind a dtype
Section titled “Inspect the values behind a dtype”An object dtype can contain strings, numbers, or other Python objects. It does not prove that every element has one type. Here the elements are all strings, so the sum concatenates them.
print("Stored dtype:", text_counts.dtype)print("Element types:", [type(value).__name__ for value in text_counts])print("String sum:", repr(text_counts.sum()))Stored dtype: objectElement types: ['str', 'str', 'str']String sum: '12045589'A CSV marker such as n/a does not necessarily make a column textual. With its default missing-value settings, pandas recognizes this marker and retains numeric values around it.
csv_text = "count\n120\nn/a\n89\n"parsed = pd.read_csv(io.StringIO(csv_text))print(parsed)print("Parsed dtype:", parsed["count"].dtype)print("Missing entries:", int(parsed["count"].isna().sum())) count0 120.01 NaN2 89.0Parsed dtype: float64Missing entries: 1Inspect the import settings, the dtype, and the actual values together. A nonstandard marker may need na_values; text identifiers may need an explicit string dtype. See NumPy Essentials for numerical array types.
Turn a numerical warning into a failure
Section titled “Turn a numerical warning into a failure”A warning allows execution to continue. Division by zero can therefore leave infinity in a result that a later calculation accepts.
numerators = np.array([10.0, 20.0, 30.0])denominators = np.array([1.0, 2.0, 0.0])with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always", RuntimeWarning) with np.errstate(divide="warn", invalid="warn"): ratios = numerators / denominators
print("Ratios:", ratios)for warning in caught: print(f"{warning.category.__name__}: {warning.message}")
try: with np.errstate(divide="raise", invalid="raise"): numerators / denominatorsexcept FloatingPointError as error: print(f"{type(error).__name__}: {error}")Ratios: [10. 10. inf]RuntimeWarning: divide by zero encountered in divideFloatingPointError: divide by zero encountered in dividenp.errstate changes NumPy’s behavior inside its context and restores the earlier settings afterward. The warning filter also affects whether repeated warnings appear. Do not infer that every later result is finite because no new warning appeared.
Validate a count vector before division
Section titled “Validate a count vector before division”This function accepts a nonempty vector of finite, nonnegative numbers with a positive total. It rejects missing measurements instead of treating them as zero or changing the denominator. A caller must resolve missing counts before requesting CPM.
def cpm(counts: object) -> np.ndarray: """Scale one complete count vector to counts per million.
Args: counts: Nonempty one-dimensional numeric counts for one sample.
Returns: A floating-point array containing counts per million.
Raises: TypeError: If the array contains nonnumeric or complex values. ValueError: If its shape, values, or library total is invalid. """ raw_counts = np.asarray(counts) if raw_counts.ndim != 1 or raw_counts.size == 0: raise ValueError("counts must be a nonempty one-dimensional vector") if raw_counts.dtype.kind not in "iuf": raise TypeError("counts must contain real numeric values") values = raw_counts.astype(float) if not np.isfinite(values).all(): raise ValueError("counts must be finite; resolve missing values first") if np.any(values < 0): raise ValueError("counts must not be negative") with np.errstate(over="ignore"): total = values.sum() if not np.isfinite(total) or total <= 0: raise ValueError("count total must be finite and positive") return values / total * 1e6
print("Valid CPM:", cpm([10, 20, 70]))invalid_inputs = [[], ["10", "20"], [-1, 10], [0, 0], [10, np.nan]]for invalid in invalid_inputs: try: cpm(invalid) except (TypeError, ValueError) as error: print(f"Rejected {invalid!r}: {type(error).__name__}: {error}")Valid CPM: [100000. 200000. 700000.]Rejected []: ValueError: counts must be a nonempty one-dimensional vectorRejected ['10', '20']: TypeError: counts must contain real numeric valuesRejected [-1, 10]: ValueError: counts must not be negativeRejected [0, 0]: ValueError: count total must be finite and positiveRejected [10, nan]: ValueError: counts must be finite; resolve missing values firstUse explicit exceptions for invalid caller input. Python can remove bare assert statements under python -O, so assertions cannot enforce this input contract. Tests still use assertions to compare a result with an independent expectation, as shown in Testing & Assertions.
Catch the failure you can handle
Section titled “Catch the failure you can handle”A broad handler can turn a programming defect into an apparently empty result. This example demonstrates that loss with a deliberately undefined name.
def broken_analysis() -> object: """Raise a deliberate name error for the exception example.
Returns: No result because the referenced name is undefined.
Raises: NameError: Always, because the demonstration contains a typo. """ return missing_result
try: result = broken_analysis()except Exception: result = Noneprint("Broad handler result:", result)
try: broken_analysis()except NameError as error: print("Visible defect:", type(error).__name__)Broad handler result: NoneVisible defect: NameErrorCatch FileNotFoundError when a missing input is an expected case. Other failures, including malformed data or an error in your own code, continue to the caller.
def read_optional_counts(path: Path) -> pd.DataFrame | None: """Read an optional CSV input.
Args: path: Path to the input CSV file.
Returns: The parsed table, or None if the file does not exist. """ try: return pd.read_csv(path) except FileNotFoundError: print(f"Missing optional input: {path.name}") return None
with TemporaryDirectory() as directory: missing_path = Path(directory) / "absent_counts.csv" print("Optional result:", read_optional_counts(missing_path))Missing optional input: absent_counts.csvOptional result: NoneReturning None is part of this function’s documented contract. For a required input, let FileNotFoundError stop the program instead.
Inspect a paused program
Section titled “Inspect a paused program”An interactive debugger lets you inspect values before the failing operation. Save the script first, then use one of these commands in your own terminal.
| Task | Command or expression |
|---|---|
| Pause at a selected source line | Insert breakpoint() before that line. |
| Run a saved script under pdb | Run uv run python -m pdb debugging_examples.py. |
| Inspect the current value | Enter p numeric_counts. |
| Execute the next line | Enter n. |
| Enter the called function | Enter s. |
| Move to the caller’s frame | Enter u. |
| Continue execution | Enter c. |
Diagnose a result that does not raise an error
Section titled “Diagnose a result that does not raise an error”A colleague wants the mean expression for each gene from rows [2, 4, 6] and [10, 10, 10].
Their calculation uses values.mean(axis=0) and returns three numbers without an exception.
State the mistaken assumption, correct the calculation, and write a check that fails for the original expression.
Do not catch an exception here because the operation itself is valid.
Open the diagnosis and regression check.
The rows represent genes, so a gene mean must reduce the sample columns with axis=1.
The expected values come from the two explicit row sums divided by three.
practice_expression = np.array([[2.0, 4.0, 6.0], [10.0, 10.0, 10.0]])wrong_means = practice_expression.mean(axis=0)gene_means = practice_expression.mean(axis=1)expected_means = np.array([4.0, 10.0])np.testing.assert_allclose(gene_means, expected_means)assert wrong_means.shape != expected_means.shapeprint("Wrong result:", wrong_means)print("Gene means:", gene_means)Wrong result: [6. 7. 8.]Gene means: [ 4. 10.]The nonsquare input exposes the error through both shape and values. On a square matrix, the shape check would pass, so retain the known numerical answer. The testing lesson shows how to put checks in a repeatable test suite. The command-line lesson applies error messages and exit statuses to a complete file conversion.
Further reading
Section titled “Further reading”The Python exception tutorial explains tracebacks and exception handlers. Its examples show which statements a try block protects and how an unmatched exception reaches its caller.
The pandas CSV reference documents missing-value markers and dtype controls. Use those options when a count column does not contain the values its source file implies.
The NumPy errstate reference explains local floating-point error settings. The Python warnings reference explains why a warning may appear once or repeatedly.
The pdb reference describes debugger commands and frame inspection. Use it when a printed value does not reveal where the value changed.