Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
How to Bind and Mock structlog Context in Python
Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.
import structlog
from unittest.mock import patch
logger = structlog.get_logger()
def demo():
logger = structlog.get_logger()
logger = logger.bind(user_id=42, request_id="abc123")
logger.info("user logged in", action="login")
# Unbind a key
logger = logger.unbind("user_id")
logger.info("r…
How to Mock Click CLI App Subcommands in Python
Simulate Click-style CLI subcommand calls in Python by using argparse with subparsers and mocking sys.argv in tests or scripts.
import sys
import argparse
def do_greet(args):
print(f"Hello, {args.name}!")
def do_goodbye(args):
print(f"Goodbye, {args.name}!")
def main():
parser = argparse.ArgumentParser(prog="clickapp")
subparsers = parser.add_subparsers(dest="command", required=True)
greet_parser = subparsers.add_par…
How to Mock Commitizen Version Bump in Python
Simulate commitizen's version bump logic and mock the subprocess call to avoid real execution in tests.
import subprocess
from unittest.mock import patch, MagicMock
def bump_version(current_version: str, increment: str = "patch") -> str:
"""Simulate commitizen's version bump logic."""
major, minor, patch = map(int, current_version.split("."))
if increment == "major":
major += 1
minor = 0
…
How to Mock Poetry pyproject.toml Dependencies Sections in Python
Parse and extract dependency lists from Poetry-style pyproject.toml text using Python's standard library.
from pathlib import Path
import re
def parse_pyproject_dependencies(text):
"""Extract dependencies from a pyproject.toml style text."""
lines = text.splitlines()
sections = {
"dependencies": [],
"dev": [],
"optional": [],
}
current_section = None
patterns = {
…
How to Parametrize Tests in Python with pytest
This code demonstrates how to use pytest's @pytest.mark.parametrize decorator to run a single test function against multiple input sets, ensuring comprehensive coverage with minimal code duplication.
import pytest
def multiply(a, b):
return a * b
@pytest.mark.parametrize("x, y, expected", [
(2, 3, 6),
(4, 5, 20),
(0, 10, 0),
(7, 1, 7),
])
def test_multiply(x, y, expected):
result = multiply(x, y)
assert result == expected, f"multiply({x}, {y}) = {result}, expected {expected}"
if _…
How to Use pytest Fixtures and conftest.py for Shared Setup in Python
Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.
import pytest
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
@pytest.fixture
def calc():
return Calculator()
@pytest.fixture
def sample_numbers():
return (3, 5)
def test_add(calc, sample_numbers):
a, b = sample_numbers
assert c…
pytest mark slow skip integration
Uses pytest markers to select fast tests, skip unfinished ones, and run integration checks with verbose output.
import pytest
def test_fast():
assert 1 + 1 == 2
@pytest.mark.slow
def test_slow():
import time
time.sleep(1)
assert 5 * 5 == 25
@pytest.mark.skip(reason="Not ready for production")
def test_skipped():
assert 2 + 2 == 5
@pytest.mark.integration
def test_integration():
database = {"users": […
Browse by section
Each section groups closely related Python snippets.
Modern tooling — Python code examples
What you will find here
This page collects modern tooling snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.