In this post we are going to cover testing, packaging and code quality in Python for data engineers: pytest, mocking external calls, fixtures and parametrize, virtual environments and lock files, uv, and linters, formatters and type hints. These are 7 real Python interview questions, asked the way they come up on a real project, and the last one is a scenario where we inherit a folder of loose Python scripts that run the nightly loads, and turn them into a maintainable project.
Pipeline code changes all the time: a new column, a new source, a library upgrade. Tests, a pinned environment and a few checks in CI are what let you change it without breaking last night's numbers. Interviewers ask about this because it shows whether you've worked on a real team codebase.
Every Python step below runs on the sample data, and the output under each step is the real result.
Part 9 of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's create some sample data
- Question 1: Your manager asks how you test data transformations before they reach production. How do you write tests with pytest?
- Question 2: A test calls a real API and fails when the network is down. How do you mock external calls?
- Question 3: Ten tests share the same sample DataFrame. How do fixtures and parametrize help?
- Question 4: The job works on your laptop but fails on the server. How do virtual environments and pinned dependencies fix it?
- Question 5: A teammate asks what uv is and whether to switch from pip. What do you say?
- Question 6: Code reviews keep arguing about style. How do linters, formatters and type hints help a data team?
- Scenario 7: You inherit a folder of loose Python scripts that run the nightly loads. How do you turn them into a maintainable project?
- The full script
The short answer
Keep transformations as pure functions and test them with pytest, mock every external call, and share sample data with fixtures and parametrize. Pin the environment with a lock file, use uv for one fast workflow, and let ruff and a type checker settle style and catch bugs in CI.
Keep that in mind. Every question below is one piece of it.
Let's create some sample data
There's no table this time. The setup writes small files into an empty folder: a transformation module, an amounts parser, an API client, their test files, and a small project called nightly-loads for the scenario. It also defines run_pytest, which runs python -m pytest -q in a child process and returns its output lines, with the run time removed so the output never changes.
import subprocess
import sys
from pathlib import Path
def write(path, text):
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")
def run_pytest(*args, cwd=None):
"""Run python -m pytest -q in a child process.
Returns its output lines, with the run time removed from the summary."""
cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", *args]
r = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd)
lines = [line for line in r.stdout.splitlines() if line.strip()]
lines[-1] = lines[-1].split(" in ")[0]
return lines
write('transform.py', '''\
import pandas as pd
def dedupe_latest(df: pd.DataFrame) -> pd.DataFrame:
"""Keep the newest version of each order."""
return (
df.sort_values(["order_id", "version"])
.drop_duplicates("order_id", keep="last")
.reset_index(drop=True)
)
''')
write('amounts.py', '''\
from decimal import Decimal
def to_cents(raw: str) -> int:
"""'1,250.00' -> 125000 and '(75.50)' -> -7550"""
text = raw.strip().replace(",", "")
if text.startswith("(") and text.endswith(")"):
text = "-" + text[1:-1]
cents = Decimal(text) * 100
if cents != cents.to_integral_value():
raise ValueError(f"more than two decimals: {raw!r}")
return int(cents)
''')
write('test_transform.py', '''\
import pandas as pd
from pandas.testing import assert_frame_equal
from transform import dedupe_latest
def test_keeps_latest_version_per_order():
raw = pd.DataFrame({"order_id": [8, 7, 7],
"version": [1, 1, 2]})
want = pd.DataFrame({"order_id": [7, 8],
"version": [2, 1]})
assert_frame_equal(dedupe_latest(raw), want)
''')
write('etl_api.py', '''\
import requests
URL = "https://api.example.com/v1/rates"
def fetch_rates(base: str) -> dict[str, float]:
r = requests.get(URL, params={"base": base}, timeout=10)
r.raise_for_status()
return r.json()["rates"]
''')
write('test_fetch.py', '''\
from unittest.mock import patch
import etl_api
def test_parses_rates():
payload = {"base": "USD", "rates": {"EUR": 0.9}}
with patch("etl_api.requests.get") as fake_get:
fake_get.return_value.json.return_value = payload
assert etl_api.fetch_rates("USD") == {"EUR": 0.9}
fake_get.assert_called_once_with(
etl_api.URL, params={"base": "USD"}, timeout=10)
''')
write('test_network.py', '''\
import pytest
import requests
import etl_api
def test_network_down(monkeypatch):
def no_network(*args, **kwargs):
raise requests.ConnectionError("network is down")
monkeypatch.setattr(etl_api.requests, "get", no_network)
with pytest.raises(requests.ConnectionError):
etl_api.fetch_rates("USD")
''')
write('conftest.py', '''\
import pandas as pd
import pytest
@pytest.fixture
def orders() -> pd.DataFrame:
"""Sample orders, built fresh for every test."""
return pd.DataFrame({
"order_id": [7, 7, 8],
"version": [1, 2, 1],
"status": ["open", "shipped", "open"],
})
''')
write('test_orders.py', '''\
from transform import dedupe_latest
def test_one_row_per_order(orders):
assert dedupe_latest(orders)["order_id"].is_unique
def test_latest_status_wins(orders):
latest = dedupe_latest(orders).set_index("order_id")
assert latest.loc[7, "status"] == "shipped"
''')
write('test_amounts.py', '''\
import pytest
from amounts import to_cents
@pytest.mark.parametrize(("raw", "expected"), [
("1,250.00", 125000),
("(75.50)", -7550),
(" 20 ", 2000),
], ids=["thousands", "negative", "spaces"])
def test_to_cents(raw, expected):
assert to_cents(raw) == expected
''')
write('nightly-loads/pyproject.toml', '''\
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "nightly-loads"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
"pandas>=3.0,<4",
"requests>=2.32,<3",
]
[project.scripts]
nightly-loads = "nightly_loads.cli:main"
[dependency-groups]
dev = ["pytest>=9", "ruff", "mypy", "pandas-stubs"]
[tool.pytest]
testpaths = ["tests"]
pythonpath = ["src"]
strict = true
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
[tool.mypy]
files = ["src"]
disallow_untyped_defs = true
''')
write('nightly-loads/src/nightly_loads/__init__.py', '''\
''')
write('nightly-loads/src/nightly_loads/transform.py', '''\
import pandas as pd
def dedupe_latest(df: pd.DataFrame) -> pd.DataFrame:
"""Keep the newest version of each order."""
return (
df.sort_values(["order_id", "version"])
.drop_duplicates("order_id", keep="last")
.reset_index(drop=True)
)
''')
write('nightly-loads/src/nightly_loads/cli.py', '''\
import argparse
import logging
logger = logging.getLogger(__name__)
def main() -> None:
parser = argparse.ArgumentParser(prog="nightly-loads")
parser.add_argument("--date", required=True)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
logger.info("nightly load for %s", args.date)
''')
write('nightly-loads/tests/test_transform.py', '''\
import pandas as pd
from nightly_loads.transform import dedupe_latest
def test_one_row_per_order():
raw = pd.DataFrame({"order_id": [7, 7, 8], "version": [1, 2, 1]})
assert dedupe_latest(raw)["order_id"].tolist() == [7, 8]
def test_latest_version_wins():
raw = pd.DataFrame({"order_id": [7, 7], "version": [1, 2]})
assert dedupe_latest(raw)["version"].tolist() == [2]
''')Question 1: Your manager asks how you test data transformations before they reach production. How do you write tests with pytest?
First, I keep each transformation as a pure function: a DataFrame goes in, a DataFrame comes out, with no files, database or network inside. Then the test is easy to write.
Here's the function. dedupe_latest keeps the newest version of each order.
import pandas as pd
def dedupe_latest(df: pd.DataFrame) -> pd.DataFrame:
"""Keep the newest version of each order."""
return (
df.sort_values(["order_id", "version"])
.drop_duplicates("order_id", keep="last")
.reset_index(drop=True)
)The test is a plain function whose name starts with test. It builds three rows by hand, with order 7 twice, and compares the result to the expected frame with assert_frame_equal. That checks the values, the column names, the dtypes and the index.
import pandas as pd
from pandas.testing import assert_frame_equal
from transform import dedupe_latest
def test_keeps_latest_version_per_order():
raw = pd.DataFrame({"order_id": [8, 7, 7],
"version": [1, 1, 2]})
want = pd.DataFrame({"order_id": [7, 8],
"version": [2, 1]})
assert_frame_equal(dedupe_latest(raw), want)Let's run pytest on that file.
# same as typing in a terminal:
# python -m pytest -q test_transform.py
print(run_pytest("test_transform.py")[-1])1 passed1 passed. When a check fails, pytest shows what differs, so you see the bug, not just a red light.
In a real project, the tests run in CI on every pull request, so a broken transformation never gets merged. And every bug you fix gets a test, so it can't come back.
Tests check the code. They don't replace data checks in the pipeline, which check each night's real data.
Question 2: A test calls a real API and fails when the network is down. How do you mock external calls?
A unit test should test my code, not the vendor's server. So we mock the external call.
Here's the code under test. fetch_rates calls requests.get with a timeout, checks the status, and returns the rates from the JSON.
import requests
URL = "https://api.example.com/v1/rates"
def fetch_rates(base: str) -> dict[str, float]:
r = requests.get(URL, params={"base": base}, timeout=10)
r.raise_for_status()
return r.json()["rates"]In the first test, patch replaces requests.get with a mock inside the with block. We set what the fake response's json method returns, call the function, and check the result. Then assert_called_once_with proves the right URL, params and timeout were sent.
from unittest.mock import patch
import etl_api
def test_parses_rates():
payload = {"base": "USD", "rates": {"EUR": 0.9}}
with patch("etl_api.requests.get") as fake_get:
fake_get.return_value.json.return_value = payload
assert etl_api.fetch_rates("USD") == {"EUR": 0.9}
fake_get.assert_called_once_with(
etl_api.URL, params={"base": "USD"}, timeout=10)The second test uses pytest's monkeypatch. It swaps get for a function that raises a ConnectionError, so we can test the network-down path without a network. Monkeypatch undoes the change after the test.
import pytest
import requests
import etl_api
def test_network_down(monkeypatch):
def no_network(*args, **kwargs):
raise requests.ConnectionError("network is down")
monkeypatch.setattr(etl_api.requests, "get", no_network)
with pytest.raises(requests.ConnectionError):
etl_api.fetch_rates("USD")Let's run both files.
# python -m pytest -q test_fetch.py test_network.py
print(run_pytest("test_fetch.py", "test_network.py")[-1])2 passed2 passed, and nothing left the machine.
The rule people miss: patch the name where your code looks it up. If the module did from requests import get, you'd patch get on that module, not on requests.
Keep a few real integration tests against a sandbox, and run them on a schedule.
Question 3: Ten tests share the same sample DataFrame. How do fixtures and parametrize help?
Copying the same DataFrame into ten tests means ten places to fix when a column changes. A fixture builds it once.
The orders fixture lives in conftest.py, so every test file in the folder can use it without an import.
import pandas as pd
import pytest
@pytest.fixture
def orders() -> pd.DataFrame:
"""Sample orders, built fresh for every test."""
return pd.DataFrame({
"order_id": [7, 7, 8],
"version": [1, 2, 1],
"status": ["open", "shipped", "open"],
})A test asks for it by name. test_one_row_per_order takes orders as an argument, and pytest passes it in. By default a fixture is built fresh for each test, so a test that changes it can't break another one.
from transform import dedupe_latest
def test_one_row_per_order(orders):
assert dedupe_latest(orders)["order_id"].is_unique
def test_latest_status_wins(orders):
latest = dedupe_latest(orders).set_index("order_id")
assert latest.loc[7, "status"] == "shipped"Parametrize is the other half: one test function, many inputs. to_cents gets three cases, thousands, negative and spaces, and the IDs we pass give each case a readable name.
import pytest
from amounts import to_cents
@pytest.mark.parametrize(("raw", "expected"), [
("1,250.00", 125000),
("(75.50)", -7550),
(" 20 ", 2000),
], ids=["thousands", "negative", "spaces"])
def test_to_cents(raw, expected):
assert to_cents(raw) == expectedLet's collect the tests in the amounts file first, and then run both files.
# python -m pytest -q --collect-only test_amounts.py
ids = run_pytest("--collect-only", "test_amounts.py")
print(*ids[:3], sep="\n")
# python -m pytest -q test_orders.py test_amounts.py
print(run_pytest("test_orders.py", "test_amounts.py")[-1])test_amounts.py::test_to_cents[thousands]
test_amounts.py::test_to_cents[negative]
test_amounts.py::test_to_cents[spaces]
5 passedpytest lists three separate test IDs: test_to_cents[thousands], test_to_cents[negative] and test_to_cents[spaces]. Running both files gives 5 passed: the two fixture tests plus the three cases.
For something like a database connection, widen the fixture scope to module or session, and use yield, so the code after the yield closes it at the end.
Question 4: The job works on your laptop but fails on the server. How do virtual environments and pinned dependencies fix it?
"Works on my laptop" usually means the two machines run different Python or package versions.
A virtual environment gives each project its own isolated packages, on the Python it was created with. Modern Debian and Ubuntu even refuse pip installs into the system Python.
# one virtual environment per project
python3.14 -m venv .venv
source .venv/bin/activate
# install exactly what the lock file says
python -m pip install -r pylock.tomlThe project declares what it needs in pyproject.toml: the minimum Python version, and dependency ranges, like pandas 3.0 or newer, but below 4.
[project]
name = "nightly-loads"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
"pandas>=3.0,<4",
"requests>=2.32,<3",
]Ranges aren't enough, because a new release can land between your test and the server's install. A lock file pins every package, including the dependencies of your dependencies, to an exact version with hashes. The standard format is pylock.toml, and the server installs from the lock file, on the same Python version. Support for it in pip is still experimental.
My tip: log the environment when the job starts. Let's print it.
import sys
from importlib.metadata import version
print("in a venv:", sys.prefix != sys.base_prefix)
print("python", sys.version.split()[0])
for pkg in ("pandas", "numpy", "requests"):
print(pkg, version(pkg))in a venv: True
python 3.14.6
pandas 3.1.0
numpy 2.5.4
requests 2.34.2Here it's a virtual environment, in a venv: True, on Python 3.14.6, with pandas 3.1.0, numpy 2.5.4 and requests 2.34.2.
Compare these lines first.
Question 5: A teammate asks what uv is and whether to switch from pip. What do you say?
uv is Astral's fast tool, written in Rust, for Python versions, virtual environments, dependencies and lock files. For most work, it replaces pip, pip-tools, virtualenv, pyenv and pipx.
| Job | Before | With uv |
|---|---|---|
| PYTHON VERSIONS | pyenv | uv python install |
| VIRTUAL ENV | python -m venv | uv sync |
| DEPENDENCIES | pip, pip-tools | uv add, uv lock |
| RUN A COMMAND | activate, then run | uv run |
The daily flow:
uv addputs a dependency inpyproject.tomland updates the lock.uv lockrefreshes it after a hand edit.uv syncbuilds the virtual environment.uv runruns a command inside it.
In CI, uv sync --locked fails if the lock file is out of date.
uv python install 3.14
uv init --package -p 3.14 nightly-loads
uv add "pandas>=3.0,<4" requests
uv add --dev pytest ruff mypy
uv lock
uv sync --locked
uv run pytest
uv export --format pylock.toml --no-dev -o pylock.tomluv keeps the dependencies in standard pyproject.toml tables. Let's read our project file back with tomllib.
import tomllib
with open("nightly-loads/pyproject.toml", "rb") as f:
project = tomllib.load(f)
print(project["project"]["dependencies"])
print(project["dependency-groups"])['pandas>=3.0,<4', 'requests>=2.32,<3']
{'dev': ['pytest>=9', 'ruff', 'mypy', 'pandas-stubs']}The dependencies sit under project: ['pandas>=3.0,<4', 'requests>=2.32,<3']. The dev tools sit under dependency-groups: {'dev': ['pytest>=9', 'ruff', 'mypy', 'pandas-stubs']}, and pip can install dependency groups too.
Two things to know:
uv.lockis specific to uv. When other tools need the lock, uv exportspylock.toml, the standard format. The last command above does that, with--no-dev, so the server's lock leaves out the dev tools.- uv is still on 0.x versions, so pin the uv version in CI.
Yes, for new projects. For existing ones, switch one repo first. pyproject.toml stays the source of truth, so pip still works.
Question 6: Code reviews keep arguing about style. How do linters, formatters and type hints help a data team?
Let tools settle style, so reviews talk about logic. A formatter rewrites the code into one standard layout, so there's nothing left to argue about. ruff format is fast and Black-compatible.
A linter finds real bugs. These are the ruff rule sets we turn on:
E,F: pycodestyle errors, unused imports, undefined namesI: import orderB: bugbear, for things like a mutable default argumentUP: modern syntax for your Python
The rules live in pyproject.toml, so everyone runs the same checks.
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
[tool.mypy]
files = ["src"]
disallow_untyped_defs = trueType hints document what a function expects, but Python doesn't enforce them at run time. Let's call count_rows, which expects a list of rows, with a file name.
def count_rows(rows: list[dict[str, object]]) -> int:
return len(rows)
print(count_rows("orders.csv")) # wrong type, no error10It returns 10, the length of the string "orders.csv", and raises no error. Mypy or pyright flags that call before the job ever runs.
Run ruff in pre-commit, and all of it in CI: ruff check, ruff format --check, mypy and pytest. A pull request that fails doesn't get merged.
# CI on every pull request (ruff in pre-commit too)
ruff check .
ruff format --check .
mypy
pytestDon't type the whole code base on day one. Require hints on new functions, and turn on stricter checks module by module.
Scenario 7: You inherit a folder of loose Python scripts that run the nightly loads. How do you turn them into a maintainable project?
Here's the plan, in order:
- Git and an inventory: reads, writes, schedule, owner.
- Characterization tests: pin today's output.
- One package under
src: extract, transform, load, config. pyproject.tomland a lock file: commands, dev group.- CI on every pull request: ruff, mypy, pytest.
- One script at a time: compare outputs, then retire.
First, nothing changes until it's safe. Put the folder in Git, and make an inventory: what each script reads, what it writes, when it runs, and who uses the output.
Then pin today's behavior. Run each script on a saved input and keep its output as the expected result. These characterization tests tell you when a refactor changes the numbers.
Now the structure: one package under src, with extract, transform and load modules, config from the environment, and logging instead of print. Shared code lives in one place, and each script becomes a thin command.
nightly-loads/
├── pyproject.toml
├── uv.lock
├── src/nightly_loads/
│ ├── __init__.py
│ ├── config.py
│ ├── extract.py
│ ├── transform.py
│ ├── load.py
│ └── cli.py
└── tests/
└── test_transform.pyThe pyproject.toml gives each job a command through [project.scripts], keeps the dev tools in a group, and holds the pytest settings under [tool.pytest], so running pytest in the project picks them up.
[project.scripts]
nightly-loads = "nightly_loads.cli:main"
[dependency-groups]
dev = ["pytest>=9", "ruff", "mypy", "pandas-stubs"]
[tool.pytest]
testpaths = ["tests"]
pythonpath = ["src"]
strict = trueLet's run pytest inside the project folder.
# cd nightly-loads && python -m pytest -q
# reads [tool.pytest] in pyproject.toml
print(run_pytest(cwd="nightly-loads")[-1])2 passed2 passed, with the project's own settings: the tests come from tests, and the package imports from src.
Last, CI runs ruff, mypy and pytest on every pull request, and the server installs from the lock file.
Run it on the same input, compare its output with the old script, then retire the old one.
Key points to remember
- Pure functions tested with pytest and assert_frame_equal
- Mock external calls: patch where the name is looked up
- Fixtures in conftest.py, many inputs with parametrize
- venv, pyproject.toml and a lock file; uv for one fast workflow
- ruff, type hints and CI on every pull request
The full script
Here is everything in one script: the sample data and every step from this post, in order. Copy it and run it top to bottom in an empty folder, because it writes small sample files.
Show the full Python script (sample data and every step)
# ========================================================================
# Python Interview Q&A #9 - Testing, packaging and code quality
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run with Python 3.14.6 and pandas 3.1.0; the outputs in the video and the blog
# post are the real outputs. Run it in an empty folder: it writes small sample files.
# ========================================================================
# Step 0: sample data
import subprocess
import sys
from pathlib import Path
def write(path, text):
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")
def run_pytest(*args, cwd=None):
"""Run python -m pytest -q in a child process.
Returns its output lines, with the run time removed from the summary."""
cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", *args]
r = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd)
lines = [line for line in r.stdout.splitlines() if line.strip()]
lines[-1] = lines[-1].split(" in ")[0]
return lines
write('transform.py', '''\
import pandas as pd
def dedupe_latest(df: pd.DataFrame) -> pd.DataFrame:
"""Keep the newest version of each order."""
return (
df.sort_values(["order_id", "version"])
.drop_duplicates("order_id", keep="last")
.reset_index(drop=True)
)
''')
write('amounts.py', '''\
from decimal import Decimal
def to_cents(raw: str) -> int:
"""'1,250.00' -> 125000 and '(75.50)' -> -7550"""
text = raw.strip().replace(",", "")
if text.startswith("(") and text.endswith(")"):
text = "-" + text[1:-1]
cents = Decimal(text) * 100
if cents != cents.to_integral_value():
raise ValueError(f"more than two decimals: {raw!r}")
return int(cents)
''')
write('test_transform.py', '''\
import pandas as pd
from pandas.testing import assert_frame_equal
from transform import dedupe_latest
def test_keeps_latest_version_per_order():
raw = pd.DataFrame({"order_id": [8, 7, 7],
"version": [1, 1, 2]})
want = pd.DataFrame({"order_id": [7, 8],
"version": [2, 1]})
assert_frame_equal(dedupe_latest(raw), want)
''')
write('etl_api.py', '''\
import requests
URL = "https://api.example.com/v1/rates"
def fetch_rates(base: str) -> dict[str, float]:
r = requests.get(URL, params={"base": base}, timeout=10)
r.raise_for_status()
return r.json()["rates"]
''')
write('test_fetch.py', '''\
from unittest.mock import patch
import etl_api
def test_parses_rates():
payload = {"base": "USD", "rates": {"EUR": 0.9}}
with patch("etl_api.requests.get") as fake_get:
fake_get.return_value.json.return_value = payload
assert etl_api.fetch_rates("USD") == {"EUR": 0.9}
fake_get.assert_called_once_with(
etl_api.URL, params={"base": "USD"}, timeout=10)
''')
write('test_network.py', '''\
import pytest
import requests
import etl_api
def test_network_down(monkeypatch):
def no_network(*args, **kwargs):
raise requests.ConnectionError("network is down")
monkeypatch.setattr(etl_api.requests, "get", no_network)
with pytest.raises(requests.ConnectionError):
etl_api.fetch_rates("USD")
''')
write('conftest.py', '''\
import pandas as pd
import pytest
@pytest.fixture
def orders() -> pd.DataFrame:
"""Sample orders, built fresh for every test."""
return pd.DataFrame({
"order_id": [7, 7, 8],
"version": [1, 2, 1],
"status": ["open", "shipped", "open"],
})
''')
write('test_orders.py', '''\
from transform import dedupe_latest
def test_one_row_per_order(orders):
assert dedupe_latest(orders)["order_id"].is_unique
def test_latest_status_wins(orders):
latest = dedupe_latest(orders).set_index("order_id")
assert latest.loc[7, "status"] == "shipped"
''')
write('test_amounts.py', '''\
import pytest
from amounts import to_cents
@pytest.mark.parametrize(("raw", "expected"), [
("1,250.00", 125000),
("(75.50)", -7550),
(" 20 ", 2000),
], ids=["thousands", "negative", "spaces"])
def test_to_cents(raw, expected):
assert to_cents(raw) == expected
''')
write('nightly-loads/pyproject.toml', '''\
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "nightly-loads"
version = "1.0.0"
requires-python = ">=3.12"
dependencies = [
"pandas>=3.0,<4",
"requests>=2.32,<3",
]
[project.scripts]
nightly-loads = "nightly_loads.cli:main"
[dependency-groups]
dev = ["pytest>=9", "ruff", "mypy", "pandas-stubs"]
[tool.pytest]
testpaths = ["tests"]
pythonpath = ["src"]
strict = true
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
[tool.mypy]
files = ["src"]
disallow_untyped_defs = true
''')
write('nightly-loads/src/nightly_loads/__init__.py', '''\
''')
write('nightly-loads/src/nightly_loads/transform.py', '''\
import pandas as pd
def dedupe_latest(df: pd.DataFrame) -> pd.DataFrame:
"""Keep the newest version of each order."""
return (
df.sort_values(["order_id", "version"])
.drop_duplicates("order_id", keep="last")
.reset_index(drop=True)
)
''')
write('nightly-loads/src/nightly_loads/cli.py', '''\
import argparse
import logging
logger = logging.getLogger(__name__)
def main() -> None:
parser = argparse.ArgumentParser(prog="nightly-loads")
parser.add_argument("--date", required=True)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
logger.info("nightly load for %s", args.date)
''')
write('nightly-loads/tests/test_transform.py', '''\
import pandas as pd
from nightly_loads.transform import dedupe_latest
def test_one_row_per_order():
raw = pd.DataFrame({"order_id": [7, 7, 8], "version": [1, 2, 1]})
assert dedupe_latest(raw)["order_id"].tolist() == [7, 8]
def test_latest_version_wins():
raw = pd.DataFrame({"order_id": [7, 7], "version": [1, 2]})
assert dedupe_latest(raw)["version"].tolist() == [2]
''')
# Step 1: Run the unit test with pytest
# same as typing in a terminal:
# python -m pytest -q test_transform.py
print(run_pytest("test_transform.py")[-1])
# Step 2: Run the mocked API tests: no network needed
# python -m pytest -q test_fetch.py test_network.py
print(run_pytest("test_fetch.py", "test_network.py")[-1])
# Step 3: List the parametrized test IDs, then run both files
# python -m pytest -q --collect-only test_amounts.py
ids = run_pytest("--collect-only", "test_amounts.py")
print(*ids[:3], sep="\n")
# python -m pytest -q test_orders.py test_amounts.py
print(run_pytest("test_orders.py", "test_amounts.py")[-1])
# Step 4: Log the environment the job really runs on
import sys
from importlib.metadata import version
print("in a venv:", sys.prefix != sys.base_prefix)
print("python", sys.version.split()[0])
for pkg in ("pandas", "numpy", "requests"):
print(pkg, version(pkg))
# Step 5: uv keeps dependencies in standard pyproject.toml tables
import tomllib
with open("nightly-loads/pyproject.toml", "rb") as f:
project = tomllib.load(f)
print(project["project"]["dependencies"])
print(project["dependency-groups"])
# Step 6: Type hints are not enforced at run time
def count_rows(rows: list[dict[str, object]]) -> int:
return len(rows)
print(count_rows("orders.csv")) # wrong type, no error
# Step 7: Run the project tests with its own [tool.pytest] settings
# cd nightly-loads && python -m pytest -q
# reads [tool.pytest] in pyproject.toml
print(run_pytest(cwd="nightly-loads")[-1])
Part 10: Real-World Manager Scenarios
The sample data on this page is invented for teaching. Every output is the real output of the code above it, run with Python 3.14.6 and pandas 3.1.0. Part of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Python and library documentation for anything you quote in an interview.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.