pyguides

Guides

Guides

In-depth guides for Python developers.

  1. Build an RSS Feed Reader in Python

    Fetch and parse RSS and Atom feeds with feedparser and httpx, handle malformed feeds, and build a CLI feed reader.

  2. Concurrent File Downloads in Python

    Build concurrent file downloads in Python with thread pools, asyncio, aiohttp, and httpx — including progress, retries, and timeouts.

  3. Build a Discord Bot with discord.py

    Make a working Discord bot in Python with discord.py — intents, events, prefix commands, and slash commands, end to end.

  4. Build an Image Resizer with Pillow

    Resize images in Python with Pillow: open, resize, save, preserve aspect ratio, fix EXIF rotation, and build a batch CLI.

  5. Build URL Shortener with Flask

    Build URL shortener with Flask and SQLite. Step-by-step tutorial covers secrets.token_urlsafe, redirects, form validation, and collision handling.

  6. Build CRUD REST APIs with FastAPI

    Learn how to build CRUD endpoints with FastAPI: path operations, Pydantic v2 request and response models, status codes, error handling, and pytest tests.

  7. Build SQLite Contacts App in Python: A Hands-On Guide

    Build SQLite apps in Python with the sqlite3 stdlib module. A CLI contacts manager with CRUD, search, and parameterized queries.

  8. contextlib Context Manager Utilities

    Master Python's contextlib context manager utilities: @contextmanager, ExitStack, suppress, nullcontext, redirect_stdout, async helpers for with statements.

  9. Build a Weather CLI with a Public API

    Walk through a Python CLI that calls the free Open-Meteo API to fetch current weather and a multi-day forecast for any city.

  10. Build Web Scrapers with BeautifulSoup

    Build web scrapers with BeautifulSoup and requests. This project walks 50 pages of books.toscrape.com, parses product cards, and exports CSV or JSON.

  11. Precise Arithmetic with the decimal Module

    Work with exact decimal numbers in Python. Learn when to reach for the decimal module, control precision and rounding, and avoid float traps in money code.

  12. Text Wrapping and Formatting with textwrap

    Text wrapping and formatting in Python: format paragraphs, help text, and log lines to a fixed width with the textwrap module and the TextWrapper class.

  13. Configuration Files with configparser

    Read, write, and validate configuration files in Python with the configparser module: sections, defaults, interpolation, and typed getters.

  14. Python Signal Handling: SIGINT, SIGTERM, and SIGHUP

    Python signal handling for SIGINT, SIGTERM, and SIGHUP — handler rules, threading caveats, and graceful shutdown patterns that work in production.

  15. Python AST Metaprogramming: How to Parse and Transform Code

    Practical Python ast metaprogramming: parse, walk, transform, and compile code with the ast module, NodeVisitor, and NodeTransformer.

  16. Binary Data with struct and memoryview

    Pack, unpack, and inspect binary data in Python with struct and memoryview. Covers format strings, byte order, and zero-copy buffer slices.

  17. Managing Dependencies in Large Projects

    Patterns and tools for managing dependencies in large Python projects: pinning, lock files (PEP 751), extras, dependency groups (PEP 735), and monorepos.

  18. Real-Time Communication with websockets

    Build real-time communication apps in Python with the websockets library: async servers, clients, broadcasts, keepalive, and gotchas.

  19. Concurrency Patterns: Threads vs Processes vs Async

    Three Python concurrency patterns — threads, processes, and asyncio — each fit a different workload. Learn when to use which model for CPU vs I/O work.

  20. Writing Python C extensions: a complete developer's guide

    Build, compile, and ship a CPython extension module in C. Covers PyMethodDef, PyModuleDef, ref counting, and the Stable ABI.

  21. Docker Python: A Practical Containerisation Guide

    A practical Docker Python guide covering Dockerfiles, base images, multi-stage builds, compose, and production hardening for Python apps.

  22. pip vs Poetry vs uv: Package Managers Compared

    pip vs Poetry vs uv: a practical comparison of Python package managers for dependency management, lockfiles, and pyproject.toml schemas.

  23. Task Queues with Celery and Redis

    Set up Celery task queues with Redis to run background jobs in Python. Covers tasks, retries, canvas primitives, and Redis broker gotchas.

  24. Working with Redis in Python: A Practical Guide to redis-py

    Connect to Redis from Python with redis-py. Covers install, sync and async clients, strings, hashes, TTL, pipelines, and connection pools.

  25. Database Migrations with Alembic

    Manage SQLAlchemy schema changes with Alembic: init, revisions, autogenerate, upgrade and downgrade, plus the gotchas that bite.

  26. SQLAlchemy Basics: ORM and Core

    Get started with SQLAlchemy 2.0: engines, Core expression language, and the typed ORM with DeclarativeBase and Mapped[].

  27. The collections Module: Beyond Lists and Dicts

    Counter, defaultdict, deque, namedtuple, ChainMap, and OrderedDict: Python's collections module containers for counting, grouping, and queuing tasks.

  28. Advanced Python Dataclass Patterns and Best Practices

    Move past boilerplate with advanced dataclass patterns: field(), __post_init__, frozen, slots, KW_ONLY, and the inheritance gotchas that bite in production.

  29. Advanced Type Hints and Protocols

    Go beyond basic annotations: Protocol, runtime_checkable, ParamSpec, TypeVarTuple, Self, TypeIs, and @override in modern Python.

  30. Python Decorators Deep Dive: From Closures to ParamSpec

    How Python decorators actually work under the hood: closures, functools.wraps, factories, class-based decorators, and typing.ParamSpec, with gotchas.

  31. Understanding Descriptors in Python

    How Python's descriptor protocol powers property, methods, and ORM fields, with worked examples of validation and lazy attributes.

  32. Rich Terminal Output in Python

    Add colored, formatted terminal output to Python CLIs with the Rich library. Covers markup, tables, progress bars, and status spinners.

  33. argparse Basics: Parsing Command-Line Arguments in Python

    Learn argparse basics in Python. Build command-line interfaces with positional and optional arguments, type conversion, default values, and help messages.

  34. NumPy Basics: Arrays and Vectorized Math

    Learn to create and manipulate NumPy arrays, perform vectorized math operations, and use broadcasting to write faster, cleaner numerical code.

  35. email module

    Parse, compose, and encode email messages in Python. Work with Message objects, MIME structures, headers, and encoding for plain-text and multipart emails.

  36. Working with FTP Servers Using Python's ftplib Module

    Connect to FTP servers, transfer files, and navigate remote directories with Python's ftplib module. Covers authentication, TLS encryption, and error handling.

  37. Build a CSV Data Analyzer

    Learn to read, filter, aggregate, and write CSV data in Python using the standard library csv module — no third-party dependencies required.

  38. Build a Markdown to HTML Converter in Python

    Learn how to convert Markdown to HTML in Python using mistune and markdown, add syntax highlighting with Pygments, and sanitize output to prevent XSS attacks.

  39. Build a Text Adventure Game

    Create an interactive fiction game in Python using dictionaries, loops, and input handling. A step-by-step guide for beginners.

  40. Python Number Guessing Game: Your First Beginner Project

    Build a Python number guessing game with variables, if/else, while loops, try/except, random.randint(), input(), int(), and functions with difficulty levels.

  41. Build a CLI task tracker app in Python

    Build a command-line task tracker in Python using argparse and JSON persistence. Subcommands, argument parsing, and disk storage explained.

  42. Build a File Organizer Script

    Learn how to write a Python script that automatically organizes files by extension, pattern, or date using pathlib, shutil, and glob.

  43. Build a Password Generator in Python

    Learn to generate cryptographically secure passwords and memorable passphrases using Python's secrets module with clear examples.

  44. Modern Python Workflow with Rye and uv

    Build a modern Python workflow with uv: replace pip, venv, and pyenv with one fast tool. Covers project setup, dependency locking, and Rye migration.

  45. Watching File Changes with watchfiles

    A practical guide to monitoring file system changes with Python's watchfiles library — covering the full API, filters, debouncing, and hot reloading workflows.

  46. Running Python Apps with Granian

    Learn how to use Granian, a Rust-based HTTP server for Python ASGI, RSGI, and WSGI applications with native HTTP/2 and WebSocket support.

  47. Result Types and Error Handling Without Exceptions

    Learn how to handle errors in Python using Result types — a functional programming pattern inspired by Rust that avoids exceptions.

  48. SQLModel: SQLAlchemy Meets Pydantic

    Learn how SQLModel unifies SQLAlchemy ORM and Pydantic validation in a single Python model class, with easy FastAPI integration.

  49. How to Check if a String is a Number in Python

    Learn multiple ways to check if a string contains a number in Python. Includes examples for integers, floats, and handling edge cases.

  50. Distributed Computing with Dask

    Learn how to scale your Python computations across multiple machines using Dask's distributed computing capabilities.

  51. Fast Serialisation with msgspec

    Learn fast serialisation with msgspec, a high-performance Python library that offers zero-copy decoding, MessagePack support, and built-in schema validation.

  52. Getting Started with Polars

    A practical guide to Polars, the fast DataFrame library for Python. Learn to create DataFrames, run queries, and use lazy execution.

  53. Building terminal UIs with Textual in Python

    Build rich terminal user interfaces in Python with the Textual framework. Covers widgets, layouts, CSS styling, events, and a practical task tracker example.

  54. attrs vs dataclasses: A Practical Comparison

    Compare Python attrs and dataclasses side-by-side—understand when to use the stdlib option versus the third-party library with more features.

  55. Runtime Type Checking with beartype

    Add runtime type safety to your Python functions with beartype—the fast, decorator-based type checker that catches type errors before they reach production.

  56. Advanced Structural Pattern Matching

    Go beyond match/case basics. Explore mapping patterns, nested structures, custom classes, and state machines.

  57. Base64 Encoding and Decoding in Python

    Learn how to encode and decode Base64 data in Python using the base64 module, with practical examples.

  58. Building CLIs with Click

    Learn how to create command-line interfaces in Python using Click, a composable and ergonomic library.

  59. Context Variables with contextvars

    Learn how to use contextvars for thread-local and task-local state in async Python. Covers ContextVar, copy_context(), and practical patterns.

  60. Dynamic Imports with importlib

    Learn to dynamically import modules and access attributes at runtime using Python's importlib.

  61. ProcessPoolExecutor and Pool in Python

    Learn how to use ProcessPoolExecutor and Pool to parallelize CPU-bound tasks. Covers pool management, mapping, and common patterns.

  62. Message Authentication with hmac

    Learn how to use Python's hmac module to create and verify keyed-hash message authentication codes (HMAC) for data integrity and authentication.

  63. Thread-Safe Queues with queue.Queue

    Learn how to use Python queue.Queue for thread-safe communication between threads. Covers FIFO, LIFO, and priority queues with practical examples.

  64. Python Security Best Practices

    Protect your Python apps from common vulnerabilities. Learn input validation, secure data handling, authentication, and defense-in-depth strategies.

  65. SSL/TLS Connections with the ssl Module

    Learn how to use Python's ssl module to create secure network connections, verify certificates, and configure TLS contexts for production use.

  66. Trio vs asyncio: Structured Concurrency in Python

    Compare Trio and asyncio for async Python. Learn when structured concurrency matters and which library fits your project.

  67. Processing CSV Files in Python

    Learn to process CSV files in Python with the csv module and pandas. Covers reading, writing, delimiters, and handling large datasets efficiently.

  68. Building APIs with FastAPI

    Learn how to create REST APIs quickly with FastAPI, from basic endpoints to parameterized routes and data validation with Pydantic.

  69. Making HTTP Requests with httpx

    Learn how to make HTTP requests in Python using httpx—a modern library supporting both sync and async APIs, HTTP/2, and a requests-compatible interface.

  70. NumPy Arrays: The Complete Guide

    Master NumPy arrays: creation, indexing, slicing, and operations for efficient numerical computing.

  71. pandas DataFrames Explained

    Master pandas DataFrames: creation, indexing, manipulation, and analysis of tabular data in Python.

  72. Subplots and Layouts in Matplotlib

    Learn how to create multiple plots in a single figure using subplots, gridspec, and layout engines.

  73. pandas groupby: Split, Apply, Combine

    Master pandas groupby operations to split data into groups, apply functions, and combine results for powerful data analysis.

  74. Profiling and Optimizing Python Code

    Learn how to identify performance bottlenecks in your Python code using profilers, and apply proven optimization techniques to make your programs run faster.

  75. Data Validation with Pydantic in Python

    Learn how to use Pydantic to validate data, define schemas, and create robust data models in your Python applications.

  76. Understanding pyproject.toml

    Learn how to configure Python projects using pyproject.toml, the modern standard for project metadata.

  77. Abstract Base Classes in Depth

    Master Python ABCs—explore advanced patterns like abstract properties, classmethods, virtual subclasses, and when to choose ABCs over Protocols.

  78. Understanding Python Bytecode

    Learn what Python bytecode is, how the interpreter compiles your code, and how to inspect and optimize by understanding what happens under the hood.

  79. Customising pickle with copyreg

    Learn to use Python's copyreg module for customising pickle serialization of classes. Register custom reducers and handle non-serializable state.

  80. csv.DictReader and csv.DictWriter

    Learn how to read and write CSV files using dictionaries with Python's csv.DictReader and csv.DictWriter classes.

  81. Understanding Python's Global Interpreter Lock (GIL)

    Understand Python's Global Interpreter Lock (GIL), why it limits threading performance, and practical strategies to work around it for CPU-bound workloads.

  82. Managing Config with python-dotenv

    Managing config with python-dotenv: load .env files, keep secrets out of code, and manage settings across development, staging, and production.

  83. Hashing with hashlib

    Learn how to use Python's hashlib module to compute cryptographic hashes, checksums, and digests for data integrity and security.

  84. Working with IP Addresses in Python

    Learn how to create, validate, and manipulate IPv4 and IPv6 addresses using Python built-in ipaddress module.

  85. Python's Memory Model and Reference Counting

    Understand how Python manages memory internally—explore reference counting, the garbage collector, and how to write memory-efficient code.

  86. Operator Overloading in Python

    Learn how to define custom behavior for Python operators in your classes using special methods like __add__, __mul__, __eq__, and more

  87. Properties: @property, getter and setter

    Learn how to use the @property decorator in Python to create managed attributes with getter, setter, and deleter methods.

  88. Generating Secrets with the secrets Module

    Learn how to generate cryptographically secure random numbers, tokens, and passwords using Python's secrets module.

  89. Persistent Storage with shelve

    Learn how to use the shelve module for simple persistent key-value storage in Python applications.

  90. Template Strings with string.Template

    Learn how to use Python's string.Template class for simple, safe string substitution without the complexity of f-strings or .format().

  91. Creating and Extracting Archives with tarfile

    Learn how to create, read, and extract tar archives using Python's tarfile module with practical examples.

  92. Generic Types and TypeVar in Python

    Master Python generics with TypeVar, Generic, and parametric polymorphism to write flexible, type-safe code that works with any data type.

  93. Compressing Data with zlib

    Learn how to compress and decompress data using Python's zlib module, the foundation for gzip and other compression formats.

  94. Making HTTP Requests with requests

    Learn how to make HTTP requests in Python using the requests library—GET, POST, headers, and error handling.

  95. Beautiful Terminal Output with Rich

    Create beautiful terminal output in Python with Rich: add colored text, tables, progress bars, syntax highlighting, and markdown rendering to CLI applications.

  96. Reading and Writing JSON Files in Python

    Working with JSON in Python using the built-in json module: read and write files, parse API responses, handle nested data, and serialize complex objects.

  97. Building CLIs with Typer

    Learn how to create elegant command-line interfaces in Python using Typer, built on Click and type hints.

  98. Python virtual environments: a practical guide

    Create and manage isolated Python virtual environments with venv. Covers activation, requirements files, common errors, and per-project best practices.

  99. Web Scraping with BeautifulSoup

    Learn the fundamentals of web scraping in Python using BeautifulSoup—parsing HTML, navigating the DOM, and extracting data.

  100. Abstract Base Classes with abc

    Learn how to use Python abc module to define abstract base classes that enforce method implementation in subclasses

  101. Async/Await Patterns in Python

    Master async/await patterns in Python—retry logic, timeouts, batching, and error handling for production async code.

  102. Getting Started with asyncio

    Learn asyncio basics—Python's library for async code. Covers coroutines, the event loop, and running concurrent operations.

  103. Building CLI Tools with argparse

    Building CLI tools with Python's argparse module: positional arguments, optional flags, type conversion, subcommands, and automatic help text.

  104. The Descriptor Protocol

    Learn how Python descriptors let you customize attribute access, create reusable property logic, and build more expressive classes.

  105. Working with Environment Variables in Python

    Learn to read, write, and manage environment variables for secure Python config. Covers os.environ, defaults, python-dotenv, and production best practices.

  106. Logging Best Practices in Python

    Take your Python logging to the next level with advanced configuration, handlers, structured logging, and production-ready patterns.

  107. Python Logging for Beginners

    Learn how to use Python logging effectively for debugging and monitoring your applications.

  108. Multiprocessing in Python

    Learn how to use Python multiprocessing to run code in parallel using multiple processes. Covers Process, Pool, shared memory, and synchronization.

  109. Mocking Pytest: A Practical Guide to Test Doubles in Python

    Mocking pytest replaces real services with controllable doubles. Covers unittest.mock, the pytest-mock fixture, patching, side effects, and assertions.

  110. Structural Subtyping with Protocol

    Learn how Protocol classes in Python enable structural subtyping, letting you define interfaces without inheritance for flexible duck typing

  111. Getting Started with pytest: The Complete Beginner's Guide

    Getting started with pytest, the most popular Python testing framework. Learn assertions, fixtures, parametrized tests, and test organization with examples.

  112. Python itertools recipes: practical patterns for iteration

    Python itertools recipes for efficient iteration: infinite sequences, grouping, combinatorics, and real-world patterns using count, cycle, groupby, and chain.

  113. Understanding Metaclasses in Python

    Dive deep into Python metaclasses—understand what they are, how they work, and when to use them to control class creation.

  114. Regular Expressions with the re Module

    Learn to use Python regular expressions for pattern matching, searching, and text manipulation.

  115. SQLite in Python with the sqlite3 Module

    Learn how to create, query, and manage SQLite databases using Python's built-in sqlite3 module.

  116. Running External Commands with subprocess

    Run external commands from Python using the subprocess module. Covers running commands, capturing output, handling errors, piping, and timeouts.

  117. Threading in Python: A Practical Guide to Concurrent Execution

    Learn Python threading to run I/O-bound tasks concurrently. Covers Thread, Lock, Queue, ThreadPoolExecutor, daemon threads, and common synchronization pitfalls.

  118. Python Unit Testing with unittest: A Complete Beginner's Guide

    Learn Python's built-in unittest framework to write and run unit tests. Covers TestCase, assertions, fixtures, mocking, test suites, and best practices.

  119. Python Enums: The enum Module

    Learn how to use Python enums to create sets of named constants with type safety and semantic meaning.

  120. f-strings: Python's String Formatting Power Tool

    Learn how to use f-strings for readable, efficient string formatting in Python.

  121. Functional Programming Patterns in Python

    Learn functional programming patterns in Python: higher-order functions, map/filter/reduce, lambdas, comprehensions, and more.

  122. A Practical Guide to functools.lru_cache in Python

    Learn how to use lru_cache to memoize function results and speed up your Python code with practical examples.

  123. Structural Pattern Matching with match/case

    Learn to use Python's structural pattern matching with match/case statements. Covers literal patterns, capturing, class matching, guards, and the as keyword.

  124. File Paths with pathlib

    Learn how to work with file paths elegantly using Python's pathlib module.

  125. Closures and Variable Scoping in Python

    Understand how closures capture variables in Python, explore the LEGB scoping rules, and apply closures in decorators, function factories, and callbacks.

  126. functools: Functional Programming Utilities

    A practical guide to Python's functools functional utilities: lru_cache, cache, partial, wraps, reduce, singledispatch, and more — with runnable examples.

  127. Building APIs with Litestar: Route Handlers, Validation, and CRUD

    Learn building APIs with Litestar, covering route handlers, request validation with Pydantic, dependency injection, controllers, and a complete CRUD example.

  128. Using namedtuple and NamedTuple in Python

    Learn how to create lightweight, immutable record types using namedtuple and NamedTuple from the Python standard library.

  129. Using __slots__ for Memory Efficiency in Python

    Python's __slots__ memory savings cut per-instance overhead by 30-50% — learn how this feature eliminates __dict__ and speeds up attribute access.

  130. Type Hints in Python

    Learn how to add type hints to your Python code for better readability and tooling support.

  131. Weak References and the weakref Module

    A practical guide to Python's weakref module: ref, proxy, WeakValueDictionary, WeakKeyDictionary, WeakSet, WeakMethod, finalize, and the __slots__ gotcha.

  132. Sorting in Python: The key= Parameter

    Learn how to use Python's key parameter for custom sorting with sorted() and list.sort(). Covers lambda functions, itemgetter, attrgetter, and multiple keys.

  133. Build a Stock Price Tracker with yfinance

    Fetch historical and live stock data with yfinance, shape it with pandas, and visualize price trends in Python.

  134. The Walrus Operator (:=) in Practice

    Learn Python walrus operator for assigning values in expressions. Covers list comprehensions, while loops, and common patterns.

  135. Context Managers and the with Statement

    Learn how Python's with statement and context managers handle resource cleanup reliably, with class-based and decorator-based examples

  136. Controlling Docker from Python

    Learn how to use the Docker SDK for Python to automate container management, including listing, running, building, and managing containers.

  137. Reading and Writing YAML in Python

    Learn how to read and write YAML files in Python using the PyYAML library, with examples for configuration files, nested data, and safe loading

  138. Error Handling with try/except

    Error handling with try/except in Python — catch exceptions gracefully, use else and finally, and create custom exception classes for domain-specific errors.

  139. List Comprehensions in Python

    Learn how to use list comprehensions to create lists concisely, with examples of filtering, nested loops, and when to prefer a regular for loop.

  140. Getting Started with Dataclasses

    Learn how to use Python dataclasses to write cleaner, more maintainable classes for storing data — with examples of defaults, immutability, and validation

  141. Python Decorators Explained

    Python decorators explained from basic wrappers to parameterized and class-based forms — practical examples for timing, logging, caching, and framework use.

  142. Virtual Environments and pip

    Virtual environments and pip give each project its own isolated dependencies — learn to create, activate, and manage environments for reproducible development.

  143. Working with files in Python: read, write, and append

    Practical guide to working with files in Python — open(), read(), write(), context managers, binary mode, pathlib, and error handling.

  144. Building a TCP Server and Client in Python

    Building TCP servers and clients in Python — covering connection handling, multi-client support with threading, and error resilience for networked applications.

  145. Understanding Python Generators

    A complete guide to generators, yield expressions, and building memory-efficient data pipelines in Python