def set_prefix(object: Memo, prefix: Optional[str]) -> None
Sets the persistence prefix for a Memo instance dynamically at runtime.
This function allows you to control which data prefix an object belongs to. This is essential for organizing data into separate partitions.
💡
This method must be called as the first statement inside the __init__ constructor of your memo class. Calling it later or outside the constructor will raise an error.
Parameters
-
objectMemo
The class instance being initialized. You should always passself. -
prefixstr, optional
The name of the prefix (scope) for the instance. IfNone, the instance will be assigned to the current default prefix.
Returns
This method does not return any value.
Example
Here’s how you can define a reusable, dynamically-scoped singleton class.
import dbzero as db0
@db0.memo(singleton=True)
class ScopedCache:
def __init__(self, prefix=None):
# This MUST be the first call in the constructor!
db0.set_prefix(self, prefix)
self.data = {}
def set(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
# --- Usage ---
# 1. Create a cache instance in a prefix named 'tenant-a-cache'
cache_a = ScopedCache(prefix="tenant-a-cache")
cache_a.set("user_count", 150)
# The object is now persisted under the 'tenant-a-cache' prefix
assert db0.get_prefix_of(cache_a).name == "tenant-a-cache"
# 2. Re-load the singleton just by specifying its prefix
del cache_a
cache_a_reopened = ScopedCache(prefix="tenant-a-cache")
assert cache_a_reopened.get("user_count") == 150
# 3. Create another, completely separate instance in a different scope
cache_b = ScopedCache(prefix="tenant-b-cache")
cache_b.set("user_count", 300)
assert db0.get_prefix_of(cache_b).name == "tenant-b-cache"
# 4. Create an instance in the current prefix by passing prefix=None
default_cache = ScopedCache(prefix=None)
assert db0.get_prefix_of(default_cache).name == db0.get_current_prefix().name