API Reference

This is the complete API reference for Nicolas Cache.

Cache Class

class nicolas.cache.Cache(backend='memory', **kwargs)

The main cache interface that provides a unified API for all backends.

Parameters:
  • backend (str) – The backend to use (“memory”, “redis”, or “redis-sentinel”)

  • kwargs (dict) – Backend-specific configuration parameters

Example:

from nicolas.cache import Cache

# Memory backend
cache = Cache(backend="memory")

# Redis backend
cache = Cache(backend="redis", host="localhost", port=6379)

# Redis Sentinel backend
cache = Cache(
    backend="redis-sentinel",
    sentinels=[("localhost", 26379)],
    service_name="mymaster"
)

Methods

Cache.get(cache_key)

Retrieve a value from the cache by key.

Parameters:

cache_key (str) – The key to retrieve

Returns:

The cached value, or None if not found

Return type:

Any

Example:

value = cache.get("user:123")
if value is None:
    # Key not found in cache
    pass
Cache.set(cache_key, value, tags=None, **kwargs)

Store a value in the cache with the given key and optional tags.

Parameters:
  • cache_key (str) – The key to store the value under

  • value (Any) – The value to store (must be pickleable)

  • tags (Optional[Iterable[str]]) – Optional tags to associate with the entry

  • ttl (Optional[int]) – Time-to-live in seconds (Redis backends only)

Example:

# Simple set
cache.set("key", "value")

# With tags
cache.set("user:123", user_data, tags=["users", "active"])

# With TTL (Redis only)
cache.set("session", session_data, ttl=3600)
Cache.delete(cache_key)

Remove an entry from the cache by its key.

Parameters:

cache_key (str) – The key to delete

Returns:

True if the key existed and was deleted, False otherwise

Return type:

bool

Example:

deleted = cache.delete("old_key")
if deleted:
    print("Key was deleted")
Cache.exists(cache_key)

Check if a key exists in the cache.

Parameters:

cache_key (str) – The key to check

Returns:

True if the key exists, False otherwise

Return type:

bool

Example:

if cache.exists("user:123"):
    user = cache.get("user:123")
Cache.get_by_tag(tag)

Retrieve all entries in the cache with a specific tag.

Parameters:

tag (str) – The tag to filter by

Returns:

Dictionary of key-value pairs

Return type:

Dict[str, Any]

Example:

active_users = cache.get_by_tag("active")
for key, user in active_users.items():
    print(f"{key}: {user['name']}")
Cache.delete_by_tag(tag)

Remove all entries from the cache with a specific tag.

Parameters:

tag (str) – The tag to filter by

Returns:

The number of entries deleted

Return type:

int

Example:

count = cache.delete_by_tag("temporary")
print(f"Deleted {count} entries")
Cache.getall()

Retrieve all entries in the cache.

Returns:

Dictionary of all key-value pairs

Return type:

Dict[str, Any]

Example:

all_data = cache.getall()
print(f"Cache contains {len(all_data)} entries")

Backend Classes

CacheBackend (Abstract Base Class)

class nicolas.CacheBackend

Abstract base class for cache backends. All backends must implement these methods.

Methods to implement:

  • get(cache_key: str) -> Any

  • get_by_tag(tag: str) -> Dict[str, Any]

  • getall() -> Dict[str, Any]

  • set(cache_key: str, value: Any, tags: Optional[Iterable[str]] = None) -> None

  • delete(cache_key: str) -> bool

  • delete_by_tag(tag: str) -> int

  • exists(cache_key: str) -> bool

MemoryCache

class nicolas.memory.MemoryCache

In-memory cache backend using Python dictionaries.

Characteristics:

  • No persistence

  • Fastest performance

  • No TTL support

  • Not shared between processes

Example:

from nicolas.memory import MemoryCache

cache = MemoryCache()
cache.set("key", "value", tags=["test"])

RedisCache

class nicolas.redis.RedisCache(host='localhost', port=6379, db=0, password=None, prefix='cache:')

Redis-based cache backend with persistence and TTL support.

Parameters:
  • host (str) – Redis server hostname

  • port (int) – Redis server port

  • db (int) – Redis database number (0-15)

  • password (Optional[str]) – Redis authentication password

  • prefix (str) – Key prefix for namespacing

Example:

from nicolas.redis import RedisCache

cache = RedisCache(
    host="redis.example.com",
    port=6379,
    password="secret",
    prefix="myapp:"
)

TTL Support:

# Set with expiration
cache.set("session", data, ttl=3600)  # Expires in 1 hour

RedisSentinelCache

class nicolas.sentinel.RedisSentinelCache(sentinels, service_name, **kwargs)

Redis Sentinel cache backend with automatic failover.

Parameters:
  • sentinels (List[Tuple[str, int]]) – List of sentinel addresses as (host, port) tuples

  • service_name (str) – Name of the Redis service in Sentinel

  • db (int) – Redis database number

  • password (Optional[str]) – Redis authentication password

  • sentinel_password (Optional[str]) – Sentinel authentication password

  • prefix (str) – Key prefix for namespacing

  • socket_timeout (float) – Socket timeout in seconds

  • socket_connect_timeout (float) – Connection timeout in seconds

  • socket_keepalive (bool) – Enable TCP keepalive

  • socket_keepalive_options (Optional[Dict[str, Any]]) – TCP keepalive options

Example:

from nicolas.sentinel import RedisSentinelCache

cache = RedisSentinelCache(
    sentinels=[
        ("sentinel1.example.com", 26379),
        ("sentinel2.example.com", 26379),
        ("sentinel3.example.com", 26379)
    ],
    service_name="mymaster",
    password="redis_password",
    sentinel_password="sentinel_password",
    socket_timeout=0.1,
    socket_keepalive=True
)

Exceptions

Nicolas Cache uses standard Python exceptions:

exception ImportError

Raised when Redis package is not installed but Redis backend is requested.

Example:

try:
    cache = Cache(backend="redis")
except ImportError as e:
    print("Redis package required: pip install redis")
exception ValueError

Raised when an unsupported backend is specified.

Example:

try:
    cache = Cache(backend="unknown")
except ValueError as e:
    print("Unsupported backend")
exception redis.ConnectionError

Raised when Redis server is not available (Redis backends only).

Example:

try:
    cache = Cache(backend="redis", host="invalid")
    cache.set("key", "value")
except redis.ConnectionError as e:
    print("Redis server not available")

Type Hints

Nicolas Cache uses type hints throughout. Here are the main types:

from typing import Any, Dict, Optional, Iterable, List, Tuple

# Cache key type
CacheKey = str

# Tag type
Tag = str

# Cache value (any pickleable object)
CacheValue = Any

# TTL in seconds
TTL = Optional[int]

# Tags collection
Tags = Optional[Iterable[Tag]]

# Sentinel addresses
SentinelAddresses = List[Tuple[str, int]]

Version Information

nicolas.__version__

The current version of Nicolas Cache.

Example:

import nicolas
print(f"Nicolas Cache version: {nicolas.__version__}")
# Output: Nicolas Cache version: 25.07.16

Constants

Default values used by the cache backends:

DEFAULT_REDIS_HOST = "localhost"
DEFAULT_REDIS_PORT = 6379
DEFAULT_REDIS_DB = 0
DEFAULT_PREFIX = "cache:"
DEFAULT_SOCKET_TIMEOUT = 0.1

Advanced Usage

Custom Backend Integration

To integrate a custom backend with the Cache class:

from nicolas import CacheBackend
from nicolas.cache import Cache

class CustomBackend(CacheBackend):
    # Implement all required methods
    pass

# Extend Cache class
class ExtendedCache(Cache):
    def __init__(self, backend="memory", **kwargs):
        if backend == "custom":
            self._backend = CustomBackend(**kwargs)
        else:
            super().__init__(backend, **kwargs)

# Use custom backend
cache = ExtendedCache(backend="custom")

Thread Safety

  • MemoryCache: Not thread-safe by default

  • RedisCache: Thread-safe

  • RedisSentinelCache: Thread-safe

For thread-safe memory caching:

import threading
from nicolas.cache import Cache

class ThreadSafeCache:
    def __init__(self):
        self.cache = Cache(backend="memory")
        self.lock = threading.RLock()

    def get(self, key):
        with self.lock:
            return self.cache.get(key)

    def set(self, key, value, **kwargs):
        with self.lock:
            return self.cache.set(key, value, **kwargs)