#python
115 snippets tagged with #python
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
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
Best for: Database session management
Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.
Best for: Domain models
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
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
LangChain Tool-Using Agent
Build a LangChain agent with custom tools for web search, calculator, and Python REPL.
Best for: AI agents
Anthropic Streaming with Python
Stream Claude responses token by token using the Anthropic Python SDK with context manager.
Best for: streaming responses
OpenAI Batch API for Cost Reduction
Submit large workloads via the OpenAI Batch API for 50% cost reduction with async processing.
Best for: batch inference
LlamaIndex Document Query Engine
Index and query documents with LlamaIndex's VectorStoreIndex for fast semantic search.
Best for: document RAG
Mistral AI API Client in Python
Make chat and embedding requests to Mistral AI using the official Python SDK.
Best for: European AI compliance
OpenAI DALL-E Image Generation
Generate and save images using the DALL-E 3 API with quality and style control.
Best for: AI image creation
Weaviate Vector Store in Python
Store, index, and perform semantic search on documents using the Weaviate Python client.
Best for: semantic search
OpenAI Assistants API with File Search
Create a persistent AI assistant with file search capability using the Assistants API v2.
Best for: document Q&A
LangChain Output Parser for Code
Parse AI-generated code blocks with LangChain's custom output parsers to extract clean code.
Best for: code extraction
Semantic Kernel Plugin in Python
Build a Semantic Kernel plugin with kernel functions that can be invoked by an AI planner.
Best for: AI orchestration
OpenAI JSON Mode Responses
Force JSON output from OpenAI models using response_format for reliable structured responses.
Best for: structured AI responses
Local LLM with Ollama Python Client
Run local open-source models with Ollama and stream responses using the Python API.
Best for: local AI
Batch Embedding Large Text Corpora
Embed thousands of documents efficiently by batching requests to the OpenAI Embeddings API.
Best for: corpus embedding
OpenAI Structured Outputs with JSON Schema
Use OpenAI's strict JSON schema mode to guarantee valid structured output from any model.
Best for: entity extraction
Prophet Time Series Forecasting
Forecast time-series data with Facebook Prophet handling holidays, trends, and seasonality.
Best for: sales forecasting
Manual OpenAI Agent Loop in Python
Implement a bare-metal AI agent loop with tool execution and conversation management without frameworks.
Best for: custom agents
Pandas DataFrame Transformations
Common pandas DataFrame transformations including column operations, type casting, and string methods.
Best for: Cleaning raw data files for analysis
Python ETL Pipeline Example
Complete extract-transform-load pipeline with error handling, logging, and incremental processing.
Best for: Automating data ingestion from CSV to warehouse
Python Batch Processing Script
Process large files in configurable batches with progress tracking, error handling, and resume support.
Best for: Processing large CSV files that don't fit in memory
Nested JSON Flattening in Python
Flatten deeply nested JSON structures into flat dictionaries suitable for DataFrames or CSV export.
Best for: Converting API responses to flat tables
Python CSV Processing Examples
Read, write, and transform CSV files using the csv module and pandas with encoding and dialect handling.
Best for: Reading and cleaning CSV data files
Data Validation with Pydantic
Validate and parse data records using Pydantic models with custom validators and error reporting.
Best for: Validating incoming data before warehouse loading
Database Sync Script in Python
Sync data between two databases with upsert logic, batch processing, and change detection.
Best for: Replicating data between databases
Python Streaming Data Processing
Process streaming data with generators, windowed aggregation, and memory-efficient line-by-line reading.
Best for: Processing large event log files efficiently
Python Data Profiling Script
Generate a data quality profile report with null counts, distributions, and anomaly detection.
Best for: Automated data quality reporting
Kafka Consumer in Python — Stream Processing
Build a Kafka consumer in Python with offset management, error handling, and batch processing.
Best for: Real-time event processing from Kafka topics
DuckDB — Query Parquet Files with Python
Use DuckDB to query Parquet files and CSVs directly from Python without loading into memory first.
Best for: Ad-hoc analytics on Parquet files without Spark
Redis Cache-Aside Pattern in Python
Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.
Best for: query caching