Lesson · 40 min · Free
Clean Code Documentation
Clean Code & Documentation As you move from writing scripts for yourself to writing code used by teammates, lab collaborators, or future-you-six-months-later, the quality of your code becomes as important as whether
Clean Code & Documentation
As you move from writing scripts for yourself to writing code used by teammates, lab collaborators, or future-you-six-months-later, the quality of your code becomes as important as whether it simply "works." In pharmaceutical and data science settings, code is often reviewed by regulators, auditors, or collaborators who must be able to trust and understand exactly what it does. Clean code refers to code that is readable, predictable, and easy to modify, while documentation refers to the comments, docstrings, and naming conventions that explain why the code exists and how it should be used. The first principle of clean code is meaningful naming. A variable called d tells the reader nothing, whereas patient_dose_mg immediately communicates its purpose and units. In scientific computing, units matter enormously — a calculation mixing mg and µg can produce errors with real clinical consequences. Names should be descriptive but concise, follow Python's snake_case convention for variables and functions, and avoid abbreviations that only the author understands. The second principle is that functions should do one thing well. A function that loads a dataset, cleans it, performs a statistical test, and plots the result is difficult to test, debug, and reuse. Breaking that monolith into smaller, single-purpose functions — load_data() , remove_outliers() , run_t_test() — makes each piece independently verifiable, which is essential when your analysis must be reproducible or validated. The third principle is documentation. Python's standard mechanism is the docstring : a triple-quoted string placed immediately after a function definition that describes what the function does, its parameters, and what it returns. Comments (lines beginning with # ) should explain the reasoning behind non-obvious decisions — not restate what the code already says. A comment like # increment i next to i += 1 adds noise; a comment like # dilution factor applied per SOP QC-104 adds genuine value. Finally, remember that documentation is a living part of your code. If you change what a function does, update its docstring in the same commit. Outdated documentation is often more dangerous than no documentation, because readers trust it blindly. Many teams also adopt style guides such as PEP 8 and tools like pydocstyle or ruff to enforce consistency automatically.
Example 1: Poorly Written vs. Clean, Documented Code
# --- Before: unclear and undocumented --- def calc(x, y, z): r = (x * y) / z return r # --- After: clean, named, documented --- def calculate_dose_per_kg(weight_kg: float, total_dose_mg: float, divisor: float = 1.0) -> float: """ Calculate the dose per kilogram of body weight. Parameters ---------- weight_kg : float Patient body weight in kilograms. Must be greater than zero. total_dose_mg : float Total prescribed dose in milligrams. divisor : float, optional Correction factor to apply (default is 1.0, i.e., no correction). Returns ------- float Dose in mg per kg of body weight. Raises ------ ValueError If weight_kg is zero or negative. """ if weight_kg
Example 2: Documented Data-Cleaning Function
import pandas as pd def clean_assay_results(df: pd.DataFrame, min_absorbance: float = 0.05) -> pd.DataFrame: """ Clean raw plate-reader assay results for downstream analysis. Steps performed: 1. Drop rows with missing sample IDs (unusable records). 2. Remove readings below the instrument's detection threshold. 3. Convert absorbance values from a string column to float. Parameters ---------- df : pd.DataFrame Raw assay data with columns 'sample_id' and 'absorbance'. min_absorbance : float, optional Detection threshold; readings below this are discarded (default 0.05, per instrument specification). Returns ------- pd.DataFrame A cleaned copy of the input data. The original is not modified. """ cleaned = df.copy() # never mutate the caller's raw data # Drop rows without a sample ID — these cannot be traced to a specimen. cleaned = cleaned.dropna(subset=["sample_id"]) # Convert absorbance to numeric; invalid entries become NaN. cleaned["absorbance"] = pd.to_numeric(cleaned["absorbance"], errors="coerce") # Filter out readings below the detection limit. cleaned = cleaned[cleaned["absorbance"] >= min_absorbance] return cleaned.reset_index(drop=True)
Key Takeaways
Use descriptive, unit-aware names (e.g., dose_mg , not d ) following Python's snake_case convention. Write functions that do one thing , making them easier to test, reuse, and validate. Every public function should have a docstring covering purpose, parameters, return value, and any exceptions raised. Use comments to explain why a decision was made (e.g., SOP references, protocol steps), never to restate obvious code. Never modify input data in place; work on a copy so raw data remains intact — critical for reproducibility and audits. Keep documentation synchronized with code; outdated docstrings mislead readers and reviewers. Follow a community style guide such as PEP 8 and consider automated linters to enforce consistency.
Practice Exercise
Take the following poorly written function and rewrite it as clean, documented code: def f(a, b): t = 0; for x in a: if x > b: t = t + x; return t . Choose a meaningful function name (for example, one reflecting that it sums values above a threshold), rename the parameters and local variables descriptively, add a complete docstring with parameters, return value, and at least one raised exception for invalid input (such as an empty list), and include one comment explaining a non-obvious design decision. Then write three short test calls demonstrating typical use, an edge case, and the error case, and briefly explain in a comment why each test matters.
Watch the full lesson — free
This topic is part of The Complete Python Bootcamp: Basics to Pharma & Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →