Functions, Modules & OOP Basics
Write reusable functions, organize modules/packages, and apply classes for cleaner data tooling.
In plain words
Functions are named steps, modules are files of steps, and classes are objects that remember things and can do steps with them.
Think of it like…
A restaurant: a function is one recipe card, a module is the binder of related recipes, a package is the whole cookbook, and a class is a station (like the grill) that holds its tools and state and knows how to do several related jobs.
Where you’ve seen it
A team's churn notebook copy-pasted the same 30 lines of date parsing and outlier clipping into five notebooks. They moved it into prep/clean.py as clean_orders(df, max_amount), added three pytest tests, and imported it everywhere. When finance changed the refund rule, one edit and one test run fixed all five reports.
Words you’ll hear
- Pure function
- Returns a result from its inputs only, without changing outside state; easy to test.
- Module / package
- A
.pyfile / a directory of modules with an__init__.py(or namespace) that you import. - Class and instance
- A blueprint and an object built from it, holding attributes and methods.
- if __name__ == "__main__":
- Code that runs when the file is executed, not when imported.
Visual diagram
Theory & deep dive
Writing useful functions
Give each function one clear job, a descriptive name and type hints: def clip_outliers(s: pd.Series, lower: float = 0.01, upper: float = 0.99) -> pd.Series. Use default and keyword arguments for options, return values instead of printing, and avoid reading or changing global variables or mutating the caller's DataFrame; returning a new object or copying first (df = df.copy()) prevents surprising side effects. *args and **kwargs collect extra positional and keyword arguments when you wrap other functions.
A good docstring states what goes in and out, including units and assumptions, and a few assert statements or checks at the top (columns present, no negative amounts) turn silent errors into clear messages. Functions are first-class values, so you can pass them around: df["price"].apply(round_price) or sorted(rows, key=lambda r: r["date"]).
def clean_orders(df, max_amount=100_000): out = df.copy(); out = out[out["amount"].between(0, max_amount)]; out["city"] = out["city"].str.strip().str.title(); return out returns a new frame, leaving the input unchanged.
Modules, packages and classes
Put related functions in a module and import them with from prep.clean import clean_orders. Keep a package layout (prep/, models/, tests/), make it importable by installing it in editable mode (pip install -e .) rather than editing sys.path, and guard script code with if __name__ == "__main__": so importing a file doesn't run it. Avoid circular imports by keeping dependencies one-directional.
Use a class when behaviour needs remembered state. A scikit-learn style transformer stores learned values in fit and applies them in transform: __init__ sets options, fit(self, X) computes and stores attributes such as self.mean_, and transform(self, X) uses them. A @dataclass is a light way to hold configuration (Config(path, test_size, seed)). Reach for classes sparingly; plain functions are often clearer in data work.
class MedianImputer: def fit(self, s): self.median_ = s.median(); return self and def transform(self, s): return s.fillna(self.median_). Fit on the training data only, then apply the same median to new data.
How it works, step by step
Step 1 of 41. Find repeated or long cells
Look for cell blocks copied between notebooks or longer than a screen.
- Signal
- copy-paste
When to use it & trade-offs
What it is
A function packages a step of analysis (clean_prices(df)) behind a name, inputs and a return value. A module is a .py file of related functions you can import; a package is a folder of modules. A class bundles data with the functions that act on it, which is how scikit-learn's fit / transform objects work. These three let you move code out of a notebook into reusable, testable pieces.
Why it matters: Notebooks start as a straight line of cells and turn into 400 lines nobody can rerun. Functions and modules make analysis repeatable, let colleagues reuse your cleaning logic, and allow unit tests. Understanding classes also makes library code readable: StandardScaler().fit(X) is just an object with state (the learned mean and variance) and methods.
When to reach for it
- Shared cleaning and feature code across notebooks
- Reusable metrics and evaluation helpers
- Custom scikit-learn transformers
When to avoid or be careful
- Functions that modify their input or rely on globals
- Importing by editing
sys.pathin notebooks - Classes where a function would do
Where to put your logic
Strengths: Fast feedback and visible output.
Watch out: Hard to reuse, test and review.
Strengths: Reusable, importable, unit-testable.
Watch out: A little structure to set up.
Strengths: Group state and behaviour; compatible with scikit-learn pipelines.
Watch out: More code than a function; easy to overuse.
Interview signals & numbers to know
When this topic comes up
- “Refactor this notebook”
- “How do you structure a data science project?”
- “Write a custom transformer”
- Unit tests for data code
- Pure functions
Benchmarks & rules of thumb
- ~30 lines
- a handy upper size for one function
- 1 job
- per function
- pip install -e .
- editable install for local packages
Common mistakes & follow-ups
Common interview mistakes
- Mutating the caller's DataFrame inside a function, then wondering why the original changed.
- Putting executable code at the top level of a module, so importing it triggers a long job.
- Learning statistics (mean, scaler) on test data inside a transform instead of in fit.
Likely interviewer follow-ups
- What makes a function easy to test?
- How would you structure a repo for a small ML project?
- How does a scikit-learn transformer keep state?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Functions, Modules & OOP Basics with data science interview Q&A and hands-on practice.