Menu

Python course · Lesson 1 of 11

Python for Data Engineering

Python for Data Engineering: structuring pipeline code, data structures, generators and batching, error handling, idempotent loads, testing and orchestration.

  • Beginner
  • Pillar guide
  • 10 min read
  • Updated Oct 2026
On this page
  1. What Python does in a Data Engineering job
  2. Set up a working environment
  3. The course, lesson by lesson
  4. 1. Structure code for reuse and testing
  5. 2. Choose the right data structure
  6. 3. Read and write files safely
  7. 4. Stream data with iterators and generators
  8. 5. Handle errors and log like production code
  9. 6. Ingest from APIs
  10. 7. Use pandas where it fits
  11. 8. Test what matters
  12. 9. Make loads idempotent
  13. 10. Work with the rest of the stack
  14. The pieces together
  15. Common mistakes
  16. In an interview
  17. Learning order and checkpoints
  18. Key takeaway

Data engineers use Python less for algorithms and more for reliable plumbing: reading from sources, checking data, transforming it, loading it, and calling tools such as Spark, warehouses and orchestrators. This guide explains where Python fits in the job, walks through the course lesson by lesson in the order the skills pay off, then shows them all working together in one small job.

What Python does in a Data Engineering job

Python is the language most data platforms expose first, so it ends up as the glue between systems. Typical work, roughly in order of how often it comes up:

Work What the Python looks like Lessons
Ingestion Pull from REST APIs, SFTP drops, object storage or databases; land raw files; load into a warehouse File I/O, APIs, idempotent loader
Orchestration Airflow DAGs, Dagster assets or Prefect flows are Python files that schedule and retry tasks Functions and modules, then Airflow
Distributed processing PySpark jobs: Python drives Spark’s engine, which does the heavy lifting PySpark fundamentals
Validation and data quality Schema checks, row-level rules, reconciliation counts, quarantine of bad records Error handling and logging, testing
Small transformations pandas, Polars or DuckDB on data that fits one machine pandas
Automation Cloud SDKs (for example boto3), CLI tools, backfill scripts, housekeeping jobs Functions and modules

What Python usually should not do: large joins and aggregations row by row in a Python loop. When data lives in a warehouse, push set-based work down to SQL; when it is too big for one machine, use Spark. A good Data Engineer uses Python to move data and coordinate work, and lets the engines that are built for it do the bulk transformation. Interviewers often probe exactly this judgement (“would you do this in pandas or in SQL?”).

Set up a working environment

Use a supported Python version (3.11 or later is a safe baseline in 2026; check the status of Python versions for end-of-life dates), one virtual environment per project, and pinned dependencies:

python3 -m venv .venv            # an isolated environment for this project
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pytest "psycopg[binary]" requests pandas
pip freeze > requirements.txt    # pin exact versions so the scheduler runs what you tested

Add a linter and formatter (ruff), a type checker (mypy or pyright) and pytest to CI. Never install packages into the system Python that your operating system or scheduler uses.

The course, lesson by lesson

The lessons are ordered so that each one uses the previous ones. The order also matches how the skills show up in interviews: structure and data structures first, then I/O, streaming and failure handling, then tools and testing.

1. Structure code for reuse and testing

Keep transformations as pure functions, push file, network and database access to the edges, pass configuration and dependencies in, add type hints at module boundaries, and give each job a thin entry point.

Read: Functions, modules and reusable pipeline code · Practise: Mutable default arguments

2. Choose the right data structure

Sets for membership and deduplication, dicts for lookup, grouping and counting, heapq for top-N, deques for queues and sliding windows, tuples for fixed records and composite keys. These choices turn quadratic loops into linear ones.

Read: Python data structures for interviews · Practise: List vs tuple vs set, dict and set complexity, Shallow vs deep copy

3. Read and write files safely

Set encodings, let the csv module handle quoting, serialise dates and Decimals explicitly, stream JSON Lines and gzip, and write outputs atomically.

Read: File I/O: CSV, JSON, JSON Lines and gzip

4. Stream data with iterators and generators

Generators produce one item at a time, so you can process files, cursors and paginated APIs of any size with flat memory. Chain them, write in batches, and measure memory instead of guessing.

Read: Iterators and generators · Practise: Generators for large datasets, A 50 GB CSV with 8 GB of RAM

5. Handle errors and log like production code

Classify failures: retry transient ones, quarantine and count bad records, fail fast on systemic errors. Catch specific exceptions, chain causes, log with run context and make failures visible to the scheduler.

Read: Error handling and logging · Practise: Exceptions in production pipelines

6. Ingest from APIs

Sessions with timeouts, pagination as a generator, retries with backoff that honour Retry-After, rate limiting, incremental pulls and raw landing.

Read: Working with APIs · Practise: Retries with backoff

7. Use pandas where it fits

Explicit dtypes, keyed deduplication, validated joins and Parquet output, and knowing when DuckDB, Polars, Spark or warehouse SQL is the better tool.

Read: pandas for Data Engineers · Practise: When not to use pandas

8. Test what matters

Parametrised tests for edge cases, fixtures and tmp_path, monkeypatched network calls, and a run-twice idempotency test for every loader.

Read: Testing with pytest · Then: Testing data pipelines and CI/CD

9. Make loads idempotent

A load that can run twice without changing the result is safe to retry and backfill. It needs a natural key, a staging table and an upsert in a single transaction, a checksum and run id for bookkeeping, quarantine for bad rows, and a test that proves a rerun changes nothing. This tutorial uses everything above against PostgreSQL.

Build: Idempotent CSV loader tutorial · Read: Idempotency in data pipelines

10. Work with the rest of the stack

The pieces together

A compact ingestion job uses most of the skills above: a generator over input lines, typed parsing with specific exceptions, counted rejects, batched idempotent writes in a transaction, and a logged summary with run context. It uses SQLite so it runs anywhere; the loader tutorial builds the production version on PostgreSQL.

import io
import json
import logging
import sqlite3
import sys
from itertools import islice

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(message)s", force=True)
log = logging.getLogger("events")

def read_events(lines):
    for line_no, line in enumerate(lines, start=1):
        try:
            e = json.loads(line)
            yield (str(e["event_id"]), e["user"], int(e["amount_cents"]))
        except (json.JSONDecodeError, KeyError, ValueError, TypeError) as exc:
            log.warning("line %d rejected: %s", line_no, type(exc).__name__)

def batches(it, size):
    it = iter(it)
    while chunk := list(islice(it, size)):
        yield chunk

def run(conn, lines, run_id, batch_size=2):
    loaded = 0
    with conn:                                               # all batches commit together, or none
        for chunk in batches(read_events(lines), batch_size):
            conn.executemany("INSERT INTO events VALUES (?, ?, ?) "
                             "ON CONFLICT(event_id) DO UPDATE SET user = excluded.user, "
                             "amount_cents = excluded.amount_cents", chunk)
            loaded += len(chunk)
    log.info("run=%s loaded=%d", run_id, loaded)

source = ('{"event_id": 1, "user": "asha", "amount_cents": 1999}\n'
          '{"event_id": 2, "user": "ben", "amount_cents": "abc"}\n'
          '{"event_id": 3, "user": "chen", "amount_cents": 500}\n'
          'not json\n'
          '{"event_id": 1, "user": "asha", "amount_cents": 1999}\n')

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE events (event_id TEXT PRIMARY KEY, user TEXT, amount_cents INTEGER)")
run(conn, io.StringIO(source), "events__2026-10-05")
first = conn.execute("SELECT * FROM events ORDER BY event_id").fetchall()
run(conn, io.StringIO(source), "events__2026-10-05")        # a retry: same final state
assert conn.execute("SELECT * FROM events ORDER BY event_id").fetchall() == first
print(conn.execute("SELECT count(*), sum(amount_cents) FROM events").fetchone())
WARNING line 2 rejected: ValueError
WARNING line 4 rejected: JSONDecodeError
INFO run=events__2026-10-05 loaded=3
WARNING line 2 rejected: ValueError
WARNING line 4 rejected: JSONDecodeError
INFO run=events__2026-10-05 loaded=3
(2, 2499)

The duplicate event 1 and the retry both collapse into the same two rows, and both bad lines are reported with their line numbers instead of disappearing. The assert is the idempotency test in one line: the table after the retry equals the table after the first run. Note that loaded=3 counts rows written, including the duplicate that was upserted onto event 1; a production loader also reports how many rows actually changed.

Which lesson each line comes from:

  • read_events is a generator (lesson 4) with specific exceptions and logging (lesson 5).
  • batches is the islice batching helper (lesson 4).
  • The upsert in one transaction is the idempotency pattern (lesson 9).
  • Keeping run separate from the data source and connection is the structure from lesson 1. It is what lets the same function run against a file, an API or a test fixture.

Common mistakes

  1. Writing one long script. Reading, transforming and writing in one block cannot be tested without real files and databases. Split into pure functions with I/O at the edges.
  2. Loading everything into memory. f.readlines(), list(cursor) or pd.read_csv on a file that keeps growing works until the day it does not. Stream and batch.
  3. Plain inserts. A retry duplicates every row. Upsert or overwrite on a key, inside one transaction.
  4. except Exception: pass. Bad data disappears without a trace. Catch specific exceptions, quarantine or count, and fail past a threshold.
  5. float for money and naive datetimes. Use Decimal and timezone-aware timestamps from the moment you parse.
  6. Row-by-row Python where SQL or Spark belongs. Push large joins and aggregations to the engine.
  7. No timeouts on network calls. A requests.get without timeout= can hang a scheduled task forever.
  8. Untested reruns. Every loader needs a test that runs it twice and compares the result.

In an interview

Python rounds for Data Engineers usually mix three kinds of questions:

  • Language fundamentals: mutable vs immutable types, list vs tuple vs set, dict and set complexity, shallow vs deep copy, mutable default arguments, generators, decorators, exceptions and context managers.
  • Coding: process a list of records (group, dedupe, top-N, sessionise) with the right data structure and state its complexity. Expect “what if the input does not fit in memory?” as the follow-up.
  • Pipeline design in Python: how you would ingest a paginated API with retries, load a file idempotently, handle bad rows, test a pipeline and structure the code.

Answer pipeline questions with the mechanism and the failure mode. Not just “I would use a generator”, but “a generator keeps one row in memory, so memory is set by the batch size, not the file size. The state I keep, like a set of seen keys, still grows.” The top 50 Python interview questions for Data Engineers cover all three kinds, from beginner to experienced, and each lesson above ends with the interview angle for its topic.

Learning order and checkpoints

Step You are ready to move on when you can…
Structure Test a transformation without touching files, databases or the clock
Data structures Pick a structure and state its average and worst-case cost
Files Read a CSV with quoted newlines and a BOM correctly, and write a file atomically
Generators Process a file larger than memory, and measure the memory it used
Errors and logging Explain which failures you retry, which you quarantine and which fail the run
APIs Pull a paginated API with retries that honour Retry-After
pandas Join with validate= and say when you would use DuckDB or Spark instead
Testing Write a parametrised test and a run-twice idempotency test
Idempotency Show a test that proves a rerun changes nothing

Key takeaway

Python in Data Engineering is about moving data reliably: structured, testable code that streams instead of loading everything, fails loudly on systemic problems, quarantines bad records, and can be rerun safely. Work through the lessons in order, use each checkpoint, and revise with the Python cheat sheet.

By , Data Engineer and Founder of DataDank · Last reviewed Oct 2026 · The mini example was run with CPython 3.11.15 (/usr/bin/python3) and its bundled SQLite through scripts/verify-examples.py; the output shown is from that run. The linked lessons record their own versions.

Progress is saved in this browser only. No account needed.

Search
Filter by type