Programming Languages
From core syntax and data structures to packaging, typing, concurrency, frameworks and testing in modern Python.
A path through the Python language and the tooling around it: the basics and built-in data structures first, then modules, packaging, idioms such as decorators and generators, OOP, static typing, concurrency and a web framework. It finishes with formatting, documentation and testing so your code is ready for a team.
The subjects follow the roadmap.sh Python roadmap.
Python is a dynamically typed, interpreted language where indentation is syntax and almost everything is an object. Get comfortable in the REPL first: type an expression, see the result, and use help() and dir() to explore any object you meet.
Blocks are opened with a colon and defined by consistent indentation (four spaces by convention, never mixed with tabs). Statements end at the newline; brackets let an expression span several lines without a backslash.
A variable is just a name bound to an object; the object carries the type, not the name. Core types are int (unbounded), float, complex, bool, str, bytes and None. Know which are mutable before you share them.
if / elif / else test truthiness: empty containers, 0, "" and None are false. Since 3.10, match / case adds structural pattern matching for destructuring tuples, dicts and class instances.
Python never converts between unrelated types silently: "3" + 4 raises TypeError. Convert explicitly with int(), float(), str(), list() and friends; int("3.5") fails, so parse floats first when input may contain decimals.
Errors are raised as exception objects and caught with try / except, with optional else (ran when nothing failed) and finally (always runs). Catch the narrowest class you can handle; a bare except: also swallows KeyboardInterrupt.
Define functions with def, using defaults, keyword arguments, *args and **kwargs. Never use a mutable default like []. Learn the builtins by heart: len, range, enumerate, zip, sorted, min, max, sum, any, all, isinstance.
for iterates over any iterable rather than counting indexes; use enumerate() when you need the position and zip() to walk sequences together. while loops on a condition, and a loop else runs only if no break happened.
Strings are immutable Unicode sequences. Format with f-strings (f"{total:.2f}"), slice like lists, and lean on methods such as split, join, strip, replace and startswith. Build big strings with "".join(parts), not += in a loop.
# starts a comment that runs to the end of the line. A string literal as the first statement of a module, class or function becomes its docstring, readable through help() and documentation tools.
Besides arithmetic, note // (floor division), ** (power), % (modulo with the sign of the divisor), chained comparisons like 0 < x < 10, is for identity versus == for equality, and the walrus := that assigns inside an expression.
The @ operator means matrix multiplication (PEP 465). Built-in types do not implement it; NumPy arrays do, so a @ b replaces np.dot(a, b). Your own classes can support it by defining __matmul__.
Annotations like def area(r: float) -> float: document intent and feed type checkers and editors, but the interpreter ignores them at runtime. Use built-in generics (list[int], dict[str, int]) and X | None on modern Python.
Python ships lists, tuples, sets and dicts as built-ins, plus collections, heapq and bisect in the standard library, so you rarely write a structure from scratch. Knowing their costs (O(1) dict lookups, O(n) list.insert(0, x)) is what keeps code fast.
Ordered, mutable, dynamically sized arrays of references. Appending and popping at the end are amortised O(1); inserting or removing at the front is O(n). Slicing copies, and sort() sorts in place while sorted() returns a new list.
Immutable sequences, ideal for fixed records and multiple return values, and usable as dict keys when their items are hashable. A one-item tuple needs a trailing comma: (1,). collections.namedtuple adds field names.
Unordered collections of unique hashable items with O(1) membership tests and operators for union |, intersection & and difference -. {} is an empty dict, so write set(); frozenset is the immutable, hashable variant.
Key-value maps that keep insertion order (guaranteed since 3.7). Use .get(key, default) to avoid KeyError, .items() to iterate pairs, and collections.defaultdict or Counter for grouping and counting.
An array stores items contiguously for O(1) indexing; a linked list chains nodes for O(1) splicing but O(n) access. Python lists are arrays; for typed numeric arrays use array or NumPy, and for cheap ends use collections.deque.
A list works as a stack via append / pop. Use collections.deque for FIFO queues, heapq for a min-heap priority queue (push tuples like (priority, item)), and queue.Queue when threads share the queue.
Hash tables map keys to buckets by hash for average O(1) lookup. In Python that is dict and set; keys must be hashable and must not change their hash, which is why lists cannot be keys.
Each node keeps smaller keys on the left and larger on the right, giving O(log n) search, insert and delete while balanced but O(n) when skewed. Python has no built-in BST; bisect on a sorted list often covers the same need.
A function that calls itself on a smaller input until it hits a base case. CPython has no tail-call optimisation and a default limit around 1000 frames, so deep recursion raises RecursionError; functools.cache turns naive recursion into memoised recursion.
Learn bubble, insertion, merge and quick sort to understand O(n²) versus O(n log n). In real code use sorted() and list.sort(): Timsort is stable and fast on partly sorted data, with key= for custom ordering.
Idiomatic Python asks forgiveness rather than permission: try the operation and handle the specific exception. Raise meaningful exceptions, chain them with raise ... from err to keep the cause, and define a small hierarchy of custom exception classes for your library.
Every .py file is a module and a directory of modules is a package. import runs a module once and caches it in sys.modules; the if __name__ == "__main__": guard lets a file act as both a library and a script.
The standard library covers a lot before you install anything: pathlib, os, sys, json, datetime, collections, itertools, functools, math, random, subprocess, logging and argparse are worth knowing on sight.
Split your own code into modules and packages, import them with absolute imports, and use __init__.py to shape a package's public API. Python finds them via sys.path, so install your project in editable mode instead of hacking that list.
lambda x: x * 2 builds a small anonymous function limited to a single expression. They shine as key= arguments to sorted, min and max; once a lambda needs a name or a second line, write a def instead.
Third-party code comes from PyPI and should be installed into an isolated virtual environment per project, never into the system interpreter. Tools range from plain pip + venv to all-in-one managers that also lock dependencies and install Python versions.
The Python Package Index is the public registry pip and friends download from. Check a package's maintenance, release history and licence there before depending on it, and watch for typo-squatted names.
The default installer: pip install pkg, pip install -r requirements.txt, pip install -e . for your own project. Run it as python -m pip so it targets the interpreter you expect, and always inside a virtual environment.
A cross-language package and environment manager popular in data science because it ships prebuilt native libraries (BLAS, CUDA, GDAL). Use the conda-forge channel and avoid mixing many pip installs into a conda env.
Manages dependencies, a poetry.lock lockfile, virtual environments and publishing from one pyproject.toml. Commands like poetry add and poetry install give reproducible installs across machines.
A very fast Rust-based tool from Astral that replaces pip, venv, pip-tools and pyenv: uv init, uv add, uv run and uv python install handle projects, lockfiles and interpreters. A strong default for new projects.
A standards-focused project manager that reads PEP 621 metadata in pyproject.toml, writes a pdm.lock and supports pluggable build backends. Similar scope to Poetry, closer to the packaging PEPs.
Combines pip and virtualenv around a Pipfile and Pipfile.lock. Still found in older application repos, but newer tools have largely overtaken it for speed and standards support.
Creates isolated environments with their own site-packages. The built-in python -m venv .venv covers most needs; the virtualenv package is a faster, more configurable superset of it.
Installs and switches between multiple Python versions per user or per directory via a .python-version file, using shims on your PATH. Handy when projects pin different interpreters; uv can now do the same.
The standard config file for a Python project: [build-system] names the build backend, [project] holds name, version and dependencies, and [tool.*] tables configure ruff, pytest, mypy and others in one place.
A decorator is a callable that takes a function and returns a replacement, applied with @name above the def. They add cross-cutting behaviour such as caching, retries, timing or access checks. Wrap the inner function with functools.wraps so its name and docstring survive.
A handful of third-party packages show up in nearly every project: requests or httpx for HTTP, python-dotenv for config, rich for terminal output, NumPy and pandas for data, and click or typer for CLIs. Learn to judge a package before adding it.
An iterable gives out an iterator via __iter__; the iterator yields values from __next__ until it raises StopIteration. This protocol powers for loops, unpacking and comprehensions. Iterators are single-use, and itertools provides lazy building blocks like chain, islice and groupby.
The re module matches text patterns: re.search finds the first hit anywhere, re.fullmatch checks the whole string and re.findall / re.sub collect or replace. Write patterns as raw strings (r"\d+") and compile ones you reuse.
Names resolve by the LEGB rule: local, enclosing function, global (module), then built-in. Assigning to a name inside a function makes it local unless you declare global or nonlocal, which is why reading then assigning a global raises UnboundLocalError.
Classes bundle state and behaviour, and Python's data model lets them plug into built-in syntax through dunder methods like __len__, __eq__ and __repr__. Prefer composition and small classes; dataclasses removes most boilerplate for plain data holders.
A class statement creates a type; __init__ sets up each instance via self. Class attributes are shared by all instances, so a mutable class attribute is a classic bug. @dataclass generates __init__, __repr__ and __eq__ for you.
Subclasses extend or override a base class and call up with super(). Python supports multiple inheritance, resolved by the method resolution order (Class.__mro__). Abstract base classes from abc force subclasses to implement required methods.
Instance methods receive self, @classmethods receive the class (great for alternative constructors), and @staticmethods receive neither. Dunder methods such as __str__, __iter__ and __enter__ hook objects into language features.
Python relies on convention: a leading underscore marks something internal, and a double underscore triggers name mangling to avoid subclass clashes. Use @property to add validation or computed values without changing the attribute-style API.
[x * x for x in nums if x > 0] builds a list in one readable expression and runs faster than an equivalent append loop. The same syntax works for sets {...} and dicts {k: v ...}. Once it needs nested loops plus conditions, a regular loop is clearer.
Swap the brackets for parentheses, (x * x for x in nums), and you get a lazy generator that produces items on demand, using constant memory. Feed them straight into sum, any or max. Generator functions with yield give the same laziness for more complex logic.
Python is multi-paradigm: procedural scripts, object-oriented designs and functional style with first-class functions, map, filter, functools and immutable data all coexist. Pick the style that keeps a given piece of code simplest rather than forcing one everywhere.
The with statement guarantees setup and cleanup, such as closing files, releasing locks or rolling back transactions, even when an exception escapes. Write your own with __enter__ / __exit__ or, more simply, a generator decorated with contextlib.contextmanager.
Type hints plus a checker catch whole classes of bugs before runtime and make large codebases navigable. Adopt gradually: annotate public functions first, run a checker in CI, and tighten settings over time.
The standard-library module behind advanced hints: Optional, Literal, TypedDict, Protocol for structural typing, TypeVar and generics, Callable and Final. Many basics no longer need it thanks to list[int] and X | Y syntax.
The original Python type checker. Run mypy src/, start lenient, then enable --strict module by module. Installs third-party stubs via types-* packages when a library ships no hints.
Microsoft's fast type checker written in TypeScript, and the engine behind Pylance in VS Code. Good inference and quick feedback make it a popular alternative to mypy; configure it in pyproject.toml.
Meta's performance-oriented type checker built for very large codebases, bundled with the Pysa security analyser. Less common outside big monorepos.
Validates and parses data at runtime from type-annotated models: subclass BaseModel, and incoming dicts or JSON are coerced and checked, with clear errors. It underpins FastAPI and is ideal for settings and API payloads.
Web frameworks split into synchronous WSGI stacks, asynchronous event-loop stacks and frameworks that handle both over ASGI. Pick one of Django, Flask or FastAPI first; the others are worth knowing when a project needs their specific strengths.
A batteries-included framework with an ORM, migrations, auth, forms and an auto-generated admin. Supports async views today. The best fit for database-backed apps where you want conventions decided for you.
A small WSGI micro-framework: routing, request and response, and Jinja templates, with everything else added through extensions. Easy to start and fully under your control, at the cost of choosing each piece yourself.
An ASGI framework that uses type hints and Pydantic to validate requests and generate OpenAPI docs automatically. Accepts both async def and plain def endpoints and has a neat dependency-injection system.
A flexible WSGI framework that scales from a single-file app to a large one, with configurable routing, traversal and security policies. Smaller community than Django or Flask.
Builds interactive analytical web apps in pure Python: layouts from components, and callbacks that react to user input and update Plotly charts. Aimed at dashboards rather than general sites.
A coroutine library built on greenlets that monkey-patches the standard library so blocking code becomes cooperative. Lets older synchronous code handle many connections, but patching can surprise you.
An asyncio HTTP client and server. Its ClientSession is a common choice for making many concurrent requests; the server side offers routing, middleware and WebSockets.
One of the earliest asynchronous Python web frameworks and servers, now running on asyncio. Known for long-lived connections such as WebSockets and long polling.
An async framework with a Flask-like API and its own production-grade server, built for speed. Route handlers are async def functions that return response objects.
Choose the tool by workload: threads or asyncio for I/O-bound work like network calls, processes for CPU-bound number crunching. concurrent.futures gives one simple pool API over both threads and processes.
In standard CPython the Global Interpreter Lock lets only one thread run Python bytecode at a time, so threads do not speed up CPU-bound pure-Python code. Python 3.13+ offers an optional free-threaded build without it (PEP 703).
The threading module runs functions in OS threads that share memory. Good for overlapping blocking I/O; protect shared state with Lock, or pass work through queue.Queue. ThreadPoolExecutor is usually simpler than raw threads.
Runs work in separate processes, each with its own interpreter and GIL, so CPU-bound code scales across cores. Arguments and results are pickled between processes, so keep payloads small and guard the entry point with if __name__ == "__main__":.
asyncio runs many coroutines on one thread: async def defines them, await yields control while waiting on I/O, and asyncio.gather or TaskGroup run them concurrently. One blocking call stalls the whole event loop.
Automatic formatters and linters end style debates and catch mistakes early. Configure them in pyproject.toml, run them in a pre-commit hook and in CI, and let the tool decide layout so reviews focus on logic.
An extremely fast Rust-based linter and formatter from Astral that re-implements rules from flake8, isort, pyupgrade and many plugins. ruff check --fix and ruff format can replace several tools at once.
The opinionated formatter that offers almost no options: run black . and code looks the same everywhere. Ruff's formatter is designed to be compatible with its output.
Google's configurable formatter that reformats code to the layout it judges best under a chosen style such as pep8 or google. Useful when a team wants more knobs than black allows.
Good Python docs start with docstrings on public modules, classes and functions, then grow into a generated site with guides and an API reference. Keep examples runnable so they cannot quietly rot.
The documentation generator used by Python itself and most major libraries. Write reStructuredText or Markdown (via MyST), pull API docs from docstrings with autodoc, and publish HTML, often to Read the Docs.
Open files with with open(path, encoding="utf-8") as f: so they always close, and choose the mode deliberately ("r", "w", "a", "rb"). pathlib.Path makes paths objects with handy methods like read_text(), exists() and / joining.
Finds paths by shell-style wildcards: glob.glob("data/*.csv") or recursive "**/*.py" with recursive=True. Path.glob() and Path.rglob() do the same with path objects. Results are not sorted, so sort them if order matters.
Automated tests let you refactor without fear. Write small, fast unit tests around behaviour, isolate external services with fakes or unittest.mock, and run the suite on every push.
The de-facto test runner: plain assert statements with detailed failure output, fixtures for setup, parametrize for table-driven tests and a large plugin ecosystem. It also runs unittest-style tests.
The standard-library xUnit framework: subclass TestCase, write test_* methods with assertEqual and friends, and run python -m unittest. No install needed, but more boilerplate than pytest.
Runs interactive examples written in docstrings and checks their output, keeping documentation honest. Best for short illustrative cases; pytest can collect them with --doctest-modules.
Automates running your tests in fresh virtual environments across several Python versions or dependency sets, configured in tox.ini or pyproject.toml. Common in libraries that must support many versions; nox is a Python-scripted alternative.