🐍

Python

Modern Python patterns including async, decorators, testing fixtures, and structured logging.

100 snippets

Showing 100 of 100 snippets

pythonintermediate

Async HTTP Client with httpx

Production-ready async HTTP client using httpx with retries, timeouts, and connection pooling.

Best for: REST API consumption

#httpx#async
pythonintermediate

Retry Decorator with Exponential Backoff

Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.

Best for: Network request resilience

#decorator#retry
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

Generator Pipeline for Data Processing

Chain generators to build memory-efficient data processing pipelines for large files and streams.

Best for: Large file ETL

#generator#pipeline
pythonintermediate

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

#cache#lru
pythonbeginner

CLI Tool with argparse

Build a professional CLI tool with subcommands, typed arguments, environment variable fallbacks, and help text.

Best for: Developer tooling

#cli#argparse
pythonbeginner

Type-Safe Settings with Pydantic

Load and validate environment variables into a typed settings object using pydantic-settings with defaults.

Best for: Application configuration

#pydantic#settings
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

Structured Logging with structlog

Configure structlog for JSON-formatted structured logging with request context, timestamps, and log levels.

Best for: Application logging

#logging#structlog
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

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

#pydantic#validation
pythonintermediate

asyncio.gather Concurrent Tasks

Run multiple async operations concurrently with asyncio.gather and proper error handling.

Best for: Parallel API calls

#asyncio#concurrency
pythonbeginner

Tenacity Retry with Backoff

Add robust retry logic with exponential backoff, jitter, and conditional retry using the tenacity library.

Best for: Flaky API calls

#retry#tenacity
pythonbeginner

Rich Progress Bar for CLI

Display beautiful progress bars and status spinners in CLI applications using the Rich library.

Best for: Data processing scripts

#cli#rich
pythonbeginner

Pathlib File Operations

Modern file system operations using pathlib for reading, writing, globbing, and path manipulation.

Best for: File processing scripts

#pathlib#filesystem
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
pythonbeginner

functools.cache and lru_cache

Memoize expensive function calls with functools.cache and lru_cache for automatic result caching.

Best for: Recursive algorithms

#caching#functools
pythonintermediate

Click CLI Command Group

Build professional CLI tools with Click using command groups, options, arguments, and help text.

Best for: Developer tools

#cli#click
pythonintermediate

HTTPX Async Client with Retry

Make async HTTP requests with HTTPX featuring timeout config, retry logic, and response streaming.

Best for: API integrations

#httpx#async
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