or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-operations.mdconfiguration.mdconnection-pooling.mderror-handling.mdindex.md
tile.json

tessl/pypi-pylibmc

Quick and small memcached client for Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pylibmc@1.6.x

To install, run

npx @tessl/cli install tessl/pypi-pylibmc@1.6.0

index.mddocs/

pylibmc

A fast Python wrapper around libmemcached, providing quick and small memcached client functionality. pylibmc offers performance-optimized memcached operations with support for binary protocol, connection pooling, consistent hashing, compression, and SASL authentication.

Package Information

  • Package Name: pylibmc
  • Language: Python
  • Installation: pip install pylibmc
  • Requirements: libmemcached development libraries

Core Imports

import pylibmc

Common usage patterns:

from pylibmc import Client, ClientPool, ThreadMappedPool

Basic Usage

import pylibmc

# Create a client connection
client = pylibmc.Client(["localhost:11211"], binary=True)

# Configure behaviors for optimal performance
client.behaviors = {
    "tcp_nodelay": True,
    "ketama": True,
    "no_block": True
}

# Basic operations
client.set("key", "value", time=3600)  # Set with 1 hour expiration
value = client.get("key")  # Get value
client.delete("key")  # Delete key

# Multi operations for efficiency  
client.set_multi({"key1": "value1", "key2": "value2"})
results = client.get_multi(["key1", "key2"])

# Atomic operations
client.set("counter", "10")
client.incr("counter", 5)  # Increment by 5
client.decr("counter", 2)  # Decrement by 2

# Connection pooling for thread safety
pool = pylibmc.ClientPool()
pool.fill(client, 10)  # Fill pool with 10 clients

with pool.reserve() as pooled_client:
    pooled_client.set("pooled_key", "pooled_value")

Architecture

pylibmc provides a layered architecture for high-performance memcached access:

  • C Extension Core (_pylibmc): Direct libmemcached bindings providing raw performance
  • Python Client Wrapper (Client): Enhanced interface with behavior management and mapping operations
  • Connection Pooling (ClientPool, ThreadMappedPool): Thread-safe client sharing patterns
  • Configuration System: Comprehensive behavior and callback configuration for optimization

This design maximizes performance through C-level operations while providing Python-friendly interfaces for development productivity.

Capabilities

Utility Functions

Module-level utility functions for information and diagnostics.

def build_info() -> str:
    """Get build information string with versions and feature support."""

Administrative Functions

Server administration and monitoring operations.

def get_stats(args: str = "") -> dict:
    """Get server statistics for all connected servers."""

def disconnect_all() -> None:
    """Disconnect from all servers and close connections."""

def flush_all(time: int = 0) -> bool:
    """Flush all items from all servers."""

Auto-Configuration

Automatic configuration for cloud cache services.

def elasticache(address: str = '127.0.0.1:11211', config_key: bytes = b'cluster', 
                mc_key: str = 'AmazonElastiCache:cluster') -> Client:
    """Auto-configure client for AWS ElastiCache clusters."""

Client Operations

Core memcached operations including get, set, delete, cas, append, prepend operations. Supports both single-key and multi-key batch operations for efficiency.

def get(key: str, default=None): ...
def set(key: str, value, time: int = 0, min_compress_len: int = 0, compress_level: int = -1) -> bool: ...
def delete(key: str) -> bool: ...
def cas(key: str, value, cas: int, time: int = 0) -> bool: ...
def get_multi(keys: list, key_prefix: str = None) -> dict: ...
def set_multi(keys: dict, time: int = 0, key_prefix: str = None, min_compress_len: int = 0, compress_level: int = -1) -> list: ...

Client Operations

Connection Pooling

Thread-safe connection pooling implementations for high-concurrency applications. Includes queue-based pooling and thread-mapped pooling strategies.

class ClientPool:
    def __init__(mc=None, n_slots: int = 0): ...
    def reserve(block: bool = False): ...
    def fill(mc, n_slots: int): ...

class ThreadMappedPool:
    def __init__(master): ...
    def reserve(): ...
    def relinquish(): ...

Connection Pooling

Configuration and Behaviors

Comprehensive behavior management for performance tuning and feature configuration. Includes hash algorithms, distribution methods, timeouts, and protocol options.

def get_behaviors() -> dict: ...
def set_behaviors(behaviors: dict): ...

# Available behavior constants
hashers: dict  # Hash algorithm mappings
distributions: dict  # Distribution algorithm mappings
all_behaviors: list  # All available behavior names

Configuration

Error Handling

Complete exception hierarchy for robust error handling, covering connection issues, protocol errors, and operational failures.

class Error(Exception): ...
class CacheMiss(Error): ...
class ConnectionError(Error): ...
class ServerError(Error): ...
# ... and 20+ other specific exception types

Error Handling

Test Utilities

Development and testing utilities for creating test clients and checking server availability.

def make_test_client(cls=Client, env=None, server_type="tcp", host="127.0.0.1", 
                     port=11211, **kwds) -> Client:
    """Create test client with default configuration."""

def is_alive(addr: str) -> bool:
    """Check if memcached server at address is alive."""

def get_version(addr: str) -> str:
    """Get version string from memcached server."""

Types

class Client:
    """Main memcached client providing all operations."""
    def __init__(servers: list, behaviors: dict = None, binary: bool = False, 
                 username: str = None, password: str = None): ...

class ClientPool:
    """Queue-based client pool for thread safety."""
    def __init__(mc=None, n_slots: int = 0): ...

class ThreadMappedPool(dict):
    """Thread-mapped client pool with per-thread clients."""
    def __init__(master): ...

class BehaviorDict(dict):
    """Dictionary that syncs behavior changes to client."""
    def __init__(client, *args, **kwargs): ...