Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 2/ 160
01. Python & Data Wrangling

Functions, Modules & OOP Basics

Write reusable functions, organize modules/packages, and apply classes for cleaner data tooling.

BeginnerFunctions · Modules3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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 .py file / 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

Loading interactive 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"]).

A small, testable cleaning function

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.

Key takeaway: One job, clear inputs and outputs, no hidden side effects.

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.

A fit/transform class

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.

Key takeaway: Modules for reuse, tests for trust, classes only when state is needed.

How it works, step by step

Step 1 of 4
Refactor

1. Find repeated or long cells

Look for cell blocks copied between notebooks or longer than a screen.

30 lines of cleaning copied 5 times
Key numbers at this step
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.path in notebooks
  • Classes where a function would do

Where to put your logic

Notebook cells
Best for: Exploration and storytelling

Strengths: Fast feedback and visible output.

Watch out: Hard to reuse, test and review.

Functions in modules
Best for: Repeated cleaning, feature and metric logic

Strengths: Reusable, importable, unit-testable.

Watch out: A little structure to set up.

Classes
Best for: Objects that learn state (transformers, models) or carry config

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?
Interview tip: Show one before-and-after refactor: a copy-pasted block becomes a tested function. It demonstrates engineering discipline in a single example.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Functions, Modules & OOP Basics with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Python Fundamentals & Data Structures
Next topic
Virtual Environments & Git Version Control