#python

115 snippets tagged with #python

pythonbeginner

Dataclass with Validation

Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.

Best for: Data transfer objects

#dataclass#validation
pythonintermediate

Custom Context Manager

Context managers for resource management using both class-based and decorator approaches with error handling.

Best for: Database connection management

#context-manager#resource-management
pythonintermediate

Pytest Fixtures and Parametrize

Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.

Best for: Unit test setup

#pytest#testing
pythonintermediate

FastAPI Dependency Injection

Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.

Best for: Database session management

#fastapi#dependency-injection
pythonbeginner

Dataclasses with Post-Init Processing

Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.

Best for: Domain models

#dataclasses#python
pythonintermediate

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#context-manager
pythonintermediate

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#dataclass
pythonintermediate

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#concurrency
pythonintermediate

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#decorators
pythonbeginner

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#pathlib
pythonintermediate

Python Logging Configuration

Configure structured logging with handlers, formatters, rotation, and JSON output for production.

Best for: Production-ready structured logging

#python#logging
pythonadvanced

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#typing
pythonintermediate

Python Itertools Recipes

Practical itertools patterns for batching, flattening, grouping, and combining iterables.

Best for: Efficient batch processing of large datasets

#python#itertools
pythonbeginner

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#cli
pythonintermediate

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

#python#decorator
pythonintermediate

Dataclass with __post_init__ Validation

Add custom validation to Python dataclasses using __post_init__.

Best for: Input validation

#python#dataclass
pythonintermediate

Custom Context Manager with __enter__ / __exit__

Build reusable resource management with Python context managers.

Best for: Resource cleanup

#python#context-manager
pythonadvanced

Run Async Tasks Concurrently with gather

Execute multiple async operations concurrently using asyncio.gather.

Best for: Parallel API calls

#python#asyncio
pythonbeginner

Memoize Functions with lru_cache

Cache expensive function results automatically using functools.lru_cache.

Best for: Recursive algorithms

#python#caching
pythonintermediate

Implement the Iterator Protocol

Create custom iterators using __iter__ and __next__ for lazy evaluation.

Best for: Batch processing

#python#iterator
pythonintermediate

Type Hints with Generics

Use Python generics for type-safe reusable data structures and functions.

Best for: Reusable data structures

#python#type-hints
pythonbeginner

Run Shell Commands with subprocess

Execute external commands safely using subprocess.run in Python.

Best for: Automation scripts

#python#subprocess
pythonintermediate

Data Validation with Pydantic Models

Define and validate data models with Pydantic for type-safe Python applications.

Best for: API request validation

#python#pydantic
pythonadvanced

Descriptors and the Property Pattern

Use Python descriptors and @property for controlled attribute access.

Best for: Controlled attribute access

#python#descriptors
pythonintermediate

Optimize Memory with __slots__

Reduce memory usage for classes with many instances using __slots__.

Best for: Memory-constrained applications

#python#slots
pythonintermediate

Abstract Base Classes with abc

Define interfaces and enforce method implementation with Python's abc module.

Best for: Interface contracts

#python#abc
pythonbeginner

Walrus Operator := Patterns

Use the walrus operator (:=) for concise assignment-in-expression patterns.

Best for: Concise filtering

#python#walrus-operator
pythonintermediate

Python Enum Advanced Patterns

Use Python enums with custom values, methods, auto(), and Flag for type-safe constants.

Best for: type-safe constants

#python#enum
pythonintermediate

Frozen Dataclass for Immutable Objects

Create immutable value objects using frozen dataclasses with hash support and custom methods.

Best for: value objects

#python#dataclass
pythonintermediate

Structural Pattern Matching (match/case)

Use Python 3.10+ match/case for expressive pattern matching with guards and destructuring.

Best for: command parsing

#python#match
pythonintermediate

contextlib Utilities for Resource Management

Use contextlib for lightweight context managers, suppressing exceptions, and redirect output.

Best for: timing code

#python#contextlib
pythonbeginner

Collections Module Patterns

Use Counter, defaultdict, deque, namedtuple, and ChainMap from the collections module.

Best for: counting

#python#collections
pythonadvanced

Asyncio Semaphore and Timeout Patterns

Control concurrency with asyncio semaphores, timeouts, and task groups for robust async code.

Best for: rate limiting API calls

#python#asyncio
pythonadvanced

Protocol Classes for Structural Typing

Define interfaces with Protocol for duck-typing that works with static type checkers.

Best for: dependency injection

#python#protocol
pythonadvanced

Advanced Generators — send, yield from, close

Use generator.send(), yield from delegation, and close() for coroutine-style generators.

Best for: streaming pipelines

#python#generator
pythonbeginner

Type Hints

Advanced Python pattern: type-hints

Best for: advanced programming

#python#advanced
pythonintermediate

Dataclass

Advanced Python pattern: dataclass

Best for: advanced programming

#python#advanced
pythonadvanced

Abc Abstract

Advanced Python pattern: abc-abstract

Best for: advanced programming

#python#advanced
pythonbeginner

Enum Types

Advanced Python pattern: enum-types

Best for: advanced programming

#python#advanced
pythonintermediate

Protocol

Advanced Python pattern: protocol

Best for: advanced programming

#python#advanced
pythonadvanced

Context Manager Custom

Advanced Python pattern: context-manager-custom

Best for: advanced programming

#python#advanced
pythonbeginner

Descriptor

Advanced Python pattern: descriptor

Best for: advanced programming

#python#advanced
pythonintermediate

Metaclass

Advanced Python pattern: metaclass

Best for: advanced programming

#python#advanced
pythonadvanced

Property Setter

Advanced Python pattern: property-setter

Best for: advanced programming

#python#advanced
pythonbeginner

Classmethod Staticmethod

Advanced Python pattern: classmethod-staticmethod

Best for: advanced programming

#python#advanced
pythonintermediate

Asyncio Concurrent

Advanced Python pattern: asyncio-concurrent

Best for: advanced programming

#python#advanced
pythonadvanced

Threading Parallel

Advanced Python pattern: threading-parallel

Best for: advanced programming

#python#advanced
pythonbeginner

Multiprocessing Pool

Advanced Python pattern: multiprocessing-pool

Best for: advanced programming

#python#advanced
pythonintermediate

Queue Management

Advanced Python pattern: queue-management

Best for: advanced programming

#python#advanced
pythonadvanced

Subprocess Execution

Advanced Python pattern: subprocess-execution

Best for: advanced programming

#python#advanced
pythonbeginner

Regex Patterns

Advanced Python pattern: regex-patterns

Best for: advanced programming

#python#advanced
pythonintermediate

Logging Config

Advanced Python pattern: logging-config

Best for: advanced programming

#python#advanced
pythonadvanced

Unittest Framework

Advanced Python pattern: unittest-framework

Best for: advanced programming

#python#advanced
pythonbeginner

Pytest Fixtures

Advanced Python pattern: pytest-fixtures

Best for: advanced programming

#python#advanced
pythonintermediate

Mock Testing

Advanced Python pattern: mock-testing

Best for: advanced programming

#python#advanced
pythonadvanced

Type Checking

Advanced Python pattern: type-checking

Best for: advanced programming

#python#advanced
pythonbeginner

Mypy Validation

Advanced Python pattern: mypy-validation

Best for: advanced programming

#python#advanced
pythonintermediate

Pydantic Validation

Advanced Python pattern: pydantic-validation

Best for: advanced programming

#python#advanced
pythonadvanced

Dataclass Factory

Advanced Python pattern: dataclass-factory

Best for: advanced programming

#python#advanced
pythonbeginner

Attrs Library

Advanced Python pattern: attrs-library

Best for: advanced programming

#python#advanced
pythonintermediate

Frozen Dataclass

Advanced Python pattern: frozen-dataclass

Best for: advanced programming

#python#advanced
pythonadvanced

Slotted Class

Advanced Python pattern: slotted-class

Best for: advanced programming

#python#advanced
pythonbeginner

Metaprogramming

Advanced Python pattern: metaprogramming

Best for: advanced programming

#python#advanced
pythonintermediate

Reflection

Advanced Python pattern: reflection

Best for: advanced programming

#python#advanced
pythonadvanced

Introspection

Advanced Python pattern: introspection

Best for: advanced programming

#python#advanced
pythonbeginner

Importlib Dynamic

Advanced Python pattern: importlib-dynamic

Best for: advanced programming

#python#advanced
pythonintermediate

Pkgutil Resources

Advanced Python pattern: pkgutil-resources

Best for: advanced programming

#python#advanced
pythonadvanced

Zipfile Archive

Advanced Python pattern: zipfile-archive

Best for: advanced programming

#python#advanced
pythonbeginner

Tarfile Compression

Advanced Python pattern: tarfile-compression

Best for: advanced programming

#python#advanced
pythonintermediate

Tempfile Temp

Advanced Python pattern: tempfile-temp

Best for: advanced programming

#python#advanced
pythonadvanced

Pathlib Path

Advanced Python pattern: pathlib-path

Best for: advanced programming

#python#advanced
pythonbeginner

Shutil Fileops

Advanced Python pattern: shutil-fileops

Best for: advanced programming

#python#advanced
pythonintermediate

Glob Patterns

Advanced Python pattern: glob-patterns

Best for: advanced programming

#python#advanced
pythonadvanced

Os Environment

Advanced Python pattern: os-environment

Best for: advanced programming

#python#advanced
pythonbeginner

Sys Interpreter

Advanced Python pattern: sys-interpreter

Best for: advanced programming

#python#advanced
pythonintermediate

Builtins Override

Advanced Python pattern: builtins-override

Best for: advanced programming

#python#advanced
pythonadvanced

Abc Registry

Advanced Python pattern: abc-registry

Best for: advanced programming

#python#advanced
pythonbeginner

Functools Cache

Advanced Python pattern: functools-cache

Best for: advanced programming

#python#advanced
pythonintermediate

Itertools Combinations

Advanced Python pattern: itertools-combinations

Best for: advanced programming

#python#advanced
pythonadvanced

More Itertools

Advanced Python pattern: more-itertools

Best for: advanced programming

#python#advanced
pythonbeginner

Click Cli

Advanced Python pattern: click-cli

Best for: advanced programming

#python#advanced
pythonintermediate

Argparse Parser

Advanced Python pattern: argparse-parser

Best for: advanced programming

#python#advanced
pythonadvanced

Configparser Ini

Advanced Python pattern: configparser-ini

Best for: advanced programming

#python#advanced
pythonbeginner

Toml Config

Advanced Python pattern: toml-config

Best for: advanced programming

#python#advanced
pythonintermediate

Yaml Serialization

Advanced Python pattern: yaml-serialization

Best for: advanced programming

#python#advanced
pythonbeginner

LangChain Prompt Chain (Python)

Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.

Best for: prompt chaining

#langchain#openai
pythonintermediate

Async OpenAI Client in Python

Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.

Best for: concurrent LLM calls

#openai#async
pythonintermediate

LangChain Tool-Using Agent

Build a LangChain agent with custom tools for web search, calculator, and Python REPL.

Best for: AI agents

#langchain#agent
pythonbeginner

Anthropic Streaming with Python

Stream Claude responses token by token using the Anthropic Python SDK with context manager.

Best for: streaming responses

#anthropic#claude
pythonadvanced

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

#openai#batch
pythonintermediate

LlamaIndex Document Query Engine

Index and query documents with LlamaIndex's VectorStoreIndex for fast semantic search.

Best for: document RAG

#llamaindex#rag
pythonbeginner

Mistral AI API Client in Python

Make chat and embedding requests to Mistral AI using the official Python SDK.

Best for: European AI compliance

#mistral#llm
pythonbeginner

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

#openai#dall-e
pythonintermediate

Weaviate Vector Store in Python

Store, index, and perform semantic search on documents using the Weaviate Python client.

Best for: semantic search

#weaviate#vector-db
pythonadvanced

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

#openai#assistants
pythonintermediate

LangChain Output Parser for Code

Parse AI-generated code blocks with LangChain's custom output parsers to extract clean code.

Best for: code extraction

#langchain#output-parser
pythonadvanced

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

#semantic-kernel#plugin
pythonbeginner

OpenAI JSON Mode Responses

Force JSON output from OpenAI models using response_format for reliable structured responses.

Best for: structured AI responses

#openai#json-mode
pythonbeginner

Local LLM with Ollama Python Client

Run local open-source models with Ollama and stream responses using the Python API.

Best for: local AI

#ollama#local-llm
pythonintermediate

Batch Embedding Large Text Corpora

Embed thousands of documents efficiently by batching requests to the OpenAI Embeddings API.

Best for: corpus embedding

#openai#embeddings
pythonintermediate

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

#openai#structured-output
pythonintermediate

Prophet Time Series Forecasting

Forecast time-series data with Facebook Prophet handling holidays, trends, and seasonality.

Best for: sales forecasting

#prophet#forecasting
pythonadvanced

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

#openai#agent
pythonbeginner

Pandas DataFrame Transformations

Common pandas DataFrame transformations including column operations, type casting, and string methods.

Best for: Cleaning raw data files for analysis

#pandas#dataframe
pythonadvanced

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

#etl#pipeline
pythonintermediate

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

#batch-processing#python
pythonintermediate

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

#json#flattening
pythonbeginner

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

#csv#python
pythonintermediate

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

#validation#pydantic
pythonadvanced

Database Sync Script in Python

Sync data between two databases with upsert logic, batch processing, and change detection.

Best for: Replicating data between databases

#database#sync
pythonintermediate

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

#streaming#python
pythonintermediate

Python Data Profiling Script

Generate a data quality profile report with null counts, distributions, and anomaly detection.

Best for: Automated data quality reporting

#data-quality#profiling
pythonadvanced

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

#kafka#streaming
pythonbeginner

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

#duckdb#parquet
pythonintermediate

Redis Cache-Aside Pattern in Python

Implement cache-aside (lazy loading) with Redis and Python to accelerate repeated database queries.

Best for: query caching

#redis#caching