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 argparse nested subparsers in Python
Build an argparse parser with nested subparsers and test it using unittest.mock.patch for sys.argv and sys.stdout.
import argparse
from unittest.mock import patch
from io import StringIO
def build_parser():
parser = argparse.ArgumentParser(prog="app")
subparsers = parser.add_subparsers(dest="command", required=True)
# Outer subparser
outer = subparsers.add_parser("outer")
outer_sub = outer.add_subparsers(dest…
Mocking loguru for Structured Logging in Python
Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.
import json
import sys
from io import StringIO
from unittest.mock import patch
def mock_loguru():
# Simulate a structured logger with context binding
class StructuredLogger:
def __init__(self):
self.context = {}
def bind(self, **kwargs):
logger = StructuredLogger()
…
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.