Redis SADD SMEMBERS Set Mock in Python

A lightweight mock of Redis SADD and SMEMBERS using Python sets for testing or local caching.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 14 views 0 copies

Python code

29 lines
Python 3.9+
class RedisSetMock:
    def __init__(self):
        self.sets = {}

    def sadd(self, key, *members):
        if key not in self.sets:
            self.sets[key] = set()
        before = len(self.sets[key])
        self.sets[key].update(members)
        return len(self.sets[key]) - before

    def smembers(self, key):
        return set(self.sets.get(key, set()))


if __name__ == "__main__":
    redis_mock = RedisSetMock()

    added = redis_mock.sadd("users:online", "alice", "bob", "carol")
    print(f"Added: {added}")

    added_dup = redis_mock.sadd("users:online", "alice", "dave")
    print(f"Added (with dup): {added_dup}")

    members = redis_mock.smembers("users:online")
    print(f"Members: {sorted(members)}")

    empty = redis_mock.smembers("nonexistent")
    print(f"Non-existent key members: {empty}")

Output

stdout
Added: 3
Added (with dup): 1
Members: ['alice', 'bob', 'carol', 'dave']
Non-existent key members: set()

How it works

The RedisSetMock class stores each Redis key as a Python set, guaranteeing uniqueness. sadd uses set.update to add members and returns the count of truly new members by comparing lengths before and after. smembers returns a copy of the set or an empty set for missing keys, mimicking Redis behavior. The mock is useful for unit tests and local development without a real Redis server.

Common mistakes

  • Returning the full set size from SADD instead of the number of newly added members.
  • Returning the internal set directly, risking accidental mutation from outside code.
  • Forgetting to handle missing keys in SMEMBERS with an empty set.

Variations

  1. Use `fakeredis` library for a more comprehensive Redis mock.
  2. Store sets as lists with manual duplicate checks if you need ordered members.

Real-world use cases

  • Unit testing code that uses Redis sets without spinning up a local Redis server.
  • Simulating online user sets in a local development environment for quick prototyping.
  • Caching small in-memory sets in applications where Redis is not required for production.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Caching & Redis

Related tutorials and quizzes for this topic.