Python
Modern Python patterns including async, decorators, testing fixtures, and structured logging.
100 snippets
Showing 100 of 100 snippets
Async HTTP Client with httpx
Production-ready async HTTP client using httpx with retries, timeouts, and connection pooling.
Best for: REST API consumption
Retry Decorator with Exponential Backoff
Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.
Best for: Network request resilience
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
Generator Pipeline for Data Processing
Chain generators to build memory-efficient data processing pipelines for large files and streams.
Best for: Large file ETL
LRU Cache with TTL Support
Extend functools.lru_cache with time-based expiration for caching expensive function calls with staleness control.
Best for: Database query caching
CLI Tool with argparse
Build a professional CLI tool with subcommands, typed arguments, environment variable fallbacks, and help text.
Best for: Developer tooling
Type-Safe Settings with Pydantic
Load and validate environment variables into a typed settings object using pydantic-settings with defaults.
Best for: Application configuration
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
Structured Logging with structlog
Configure structlog for JSON-formatted structured logging with request context, timestamps, and log levels.
Best for: Application logging
FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
Best for: Database session management
Pydantic v2 Model Patterns
Define and validate data models with Pydantic v2 using field validators, computed fields, and serialization.
Best for: API request/response models
asyncio.gather Concurrent Tasks
Run multiple async operations concurrently with asyncio.gather and proper error handling.
Best for: Parallel API calls
Tenacity Retry with Backoff
Add robust retry logic with exponential backoff, jitter, and conditional retry using the tenacity library.
Best for: Flaky API calls
Rich Progress Bar for CLI
Display beautiful progress bars and status spinners in CLI applications using the Rich library.
Best for: Data processing scripts
Pathlib File Operations
Modern file system operations using pathlib for reading, writing, globbing, and path manipulation.
Best for: File processing scripts
Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.
Best for: Domain models
functools.cache and lru_cache
Memoize expensive function calls with functools.cache and lru_cache for automatic result caching.
Best for: Recursive algorithms
Click CLI Command Group
Build professional CLI tools with Click using command groups, options, arguments, and help text.
Best for: Developer tools
HTTPX Async Client with Retry
Make async HTTP requests with HTTPX featuring timeout config, retry logic, and response streaming.
Best for: API integrations
Python Context Manager Patterns
Create custom context managers with __enter__/__exit__ and contextlib for resource management.
Best for: Automatic resource cleanup and lifecycle management
Python Dataclass Advanced Patterns
Advanced dataclass usage with validation, post-init processing, slots, and frozen instances.
Best for: Type-safe data models without ORMs
Python Concurrent Futures for Parallel Work
Run tasks in parallel using ThreadPoolExecutor and ProcessPoolExecutor with error handling.
Best for: Parallel HTTP requests for web scraping
Python Functools and Decorator Patterns
Useful decorator patterns with functools including caching, retry, timing, and rate limiting.
Best for: Adding retry logic to flaky operations
Python Pathlib File Operations
Modern file system operations using pathlib for cross-platform path handling and file management.
Best for: Cross-platform file path handling
Python Logging Configuration
Configure structured logging with handlers, formatters, rotation, and JSON output for production.
Best for: Production-ready structured logging
Python Advanced Typing Patterns
Advanced type hints with Protocol, TypeVar, Generic, overload, and TypeGuard for safer code.
Best for: Building type-safe generic containers
Python Itertools Recipes
Practical itertools patterns for batching, flattening, grouping, and combining iterables.
Best for: Efficient batch processing of large datasets
Python CLI Tool with Argparse
Build a command-line tool with subcommands, arguments, validation, and help text using argparse.
Best for: Building developer tooling CLIs
Python Retry Decorator with Backoff
Create a retry decorator with exponential backoff and configurable attempts for flaky operations.
Best for: Resilient HTTP requests to external APIs
Dataclass with __post_init__ Validation
Add custom validation to Python dataclasses using __post_init__.
Best for: Input validation
Custom Context Manager with __enter__ / __exit__
Build reusable resource management with Python context managers.
Best for: Resource cleanup
Run Async Tasks Concurrently with gather
Execute multiple async operations concurrently using asyncio.gather.
Best for: Parallel API calls
Memoize Functions with lru_cache
Cache expensive function results automatically using functools.lru_cache.
Best for: Recursive algorithms
Implement the Iterator Protocol
Create custom iterators using __iter__ and __next__ for lazy evaluation.
Best for: Batch processing
Type Hints with Generics
Use Python generics for type-safe reusable data structures and functions.
Best for: Reusable data structures
Run Shell Commands with subprocess
Execute external commands safely using subprocess.run in Python.
Best for: Automation scripts
Data Validation with Pydantic Models
Define and validate data models with Pydantic for type-safe Python applications.
Best for: API request validation
Descriptors and the Property Pattern
Use Python descriptors and @property for controlled attribute access.
Best for: Controlled attribute access
Optimize Memory with __slots__
Reduce memory usage for classes with many instances using __slots__.
Best for: Memory-constrained applications
Abstract Base Classes with abc
Define interfaces and enforce method implementation with Python's abc module.
Best for: Interface contracts
Walrus Operator := Patterns
Use the walrus operator (:=) for concise assignment-in-expression patterns.
Best for: Concise filtering
Python Enum Advanced Patterns
Use Python enums with custom values, methods, auto(), and Flag for type-safe constants.
Best for: type-safe constants
Frozen Dataclass for Immutable Objects
Create immutable value objects using frozen dataclasses with hash support and custom methods.
Best for: value objects
Structural Pattern Matching (match/case)
Use Python 3.10+ match/case for expressive pattern matching with guards and destructuring.
Best for: command parsing
contextlib Utilities for Resource Management
Use contextlib for lightweight context managers, suppressing exceptions, and redirect output.
Best for: timing code
Collections Module Patterns
Use Counter, defaultdict, deque, namedtuple, and ChainMap from the collections module.
Best for: counting
Asyncio Semaphore and Timeout Patterns
Control concurrency with asyncio semaphores, timeouts, and task groups for robust async code.
Best for: rate limiting API calls
Protocol Classes for Structural Typing
Define interfaces with Protocol for duck-typing that works with static type checkers.
Best for: dependency injection
Advanced Generators — send, yield from, close
Use generator.send(), yield from delegation, and close() for coroutine-style generators.
Best for: streaming pipelines
Type Hints
Advanced Python pattern: type-hints
Best for: advanced programming
Dataclass
Advanced Python pattern: dataclass
Best for: advanced programming
Abc Abstract
Advanced Python pattern: abc-abstract
Best for: advanced programming
Enum Types
Advanced Python pattern: enum-types
Best for: advanced programming
Protocol
Advanced Python pattern: protocol
Best for: advanced programming
Context Manager Custom
Advanced Python pattern: context-manager-custom
Best for: advanced programming
Descriptor
Advanced Python pattern: descriptor
Best for: advanced programming
Metaclass
Advanced Python pattern: metaclass
Best for: advanced programming
Property Setter
Advanced Python pattern: property-setter
Best for: advanced programming
Classmethod Staticmethod
Advanced Python pattern: classmethod-staticmethod
Best for: advanced programming
Asyncio Concurrent
Advanced Python pattern: asyncio-concurrent
Best for: advanced programming
Threading Parallel
Advanced Python pattern: threading-parallel
Best for: advanced programming
Multiprocessing Pool
Advanced Python pattern: multiprocessing-pool
Best for: advanced programming
Queue Management
Advanced Python pattern: queue-management
Best for: advanced programming
Subprocess Execution
Advanced Python pattern: subprocess-execution
Best for: advanced programming
Regex Patterns
Advanced Python pattern: regex-patterns
Best for: advanced programming
Logging Config
Advanced Python pattern: logging-config
Best for: advanced programming
Unittest Framework
Advanced Python pattern: unittest-framework
Best for: advanced programming
Pytest Fixtures
Advanced Python pattern: pytest-fixtures
Best for: advanced programming
Mock Testing
Advanced Python pattern: mock-testing
Best for: advanced programming
Type Checking
Advanced Python pattern: type-checking
Best for: advanced programming
Mypy Validation
Advanced Python pattern: mypy-validation
Best for: advanced programming
Pydantic Validation
Advanced Python pattern: pydantic-validation
Best for: advanced programming
Dataclass Factory
Advanced Python pattern: dataclass-factory
Best for: advanced programming
Attrs Library
Advanced Python pattern: attrs-library
Best for: advanced programming
Frozen Dataclass
Advanced Python pattern: frozen-dataclass
Best for: advanced programming
Slotted Class
Advanced Python pattern: slotted-class
Best for: advanced programming
Metaprogramming
Advanced Python pattern: metaprogramming
Best for: advanced programming
Reflection
Advanced Python pattern: reflection
Best for: advanced programming
Introspection
Advanced Python pattern: introspection
Best for: advanced programming
Importlib Dynamic
Advanced Python pattern: importlib-dynamic
Best for: advanced programming
Pkgutil Resources
Advanced Python pattern: pkgutil-resources
Best for: advanced programming
Zipfile Archive
Advanced Python pattern: zipfile-archive
Best for: advanced programming
Tarfile Compression
Advanced Python pattern: tarfile-compression
Best for: advanced programming
Tempfile Temp
Advanced Python pattern: tempfile-temp
Best for: advanced programming
Pathlib Path
Advanced Python pattern: pathlib-path
Best for: advanced programming
Shutil Fileops
Advanced Python pattern: shutil-fileops
Best for: advanced programming
Glob Patterns
Advanced Python pattern: glob-patterns
Best for: advanced programming
Os Environment
Advanced Python pattern: os-environment
Best for: advanced programming
Sys Interpreter
Advanced Python pattern: sys-interpreter
Best for: advanced programming
Builtins Override
Advanced Python pattern: builtins-override
Best for: advanced programming
Abc Registry
Advanced Python pattern: abc-registry
Best for: advanced programming
Functools Cache
Advanced Python pattern: functools-cache
Best for: advanced programming
Itertools Combinations
Advanced Python pattern: itertools-combinations
Best for: advanced programming
More Itertools
Advanced Python pattern: more-itertools
Best for: advanced programming
Click Cli
Advanced Python pattern: click-cli
Best for: advanced programming
Argparse Parser
Advanced Python pattern: argparse-parser
Best for: advanced programming
Configparser Ini
Advanced Python pattern: configparser-ini
Best for: advanced programming
Toml Config
Advanced Python pattern: toml-config
Best for: advanced programming
Yaml Serialization
Advanced Python pattern: yaml-serialization
Best for: advanced programming