def fetch(identifier: Union[str, type], expected_type: Optional[type], prefix: Optional[str]) -> Memo
Retrieve a dbzero object instance by its UUID or type (for singletons).
This is the fastest way to access an object, operating in constant time O(1). It is guaranteed that only one instance of an object exists for a given UUID. If the object isn't found in the cache, dbzero will attempt to load it from the persistence layer, which involve performing I/O operations.
Parameters
-
identifierstr or type
The identifier for the object you want to retrieve.- UUID string: Returns the specific object instance for that UUID.
- type (singleton class): Returns the unique instance of that singleton for the current prefix.
-
expected_typetype, optional
Optional type to validate the retrieved object. Raises exception if the fetched object is not an instance of this type. This is useful for ensuring type safety. -
prefixstr, optional
Optional name of the data prefix to fetch the object from. Used for retrieving singletons from non-default prefixes, as singletons are unique per prefix.
Returns
The requested Memo object instance. Subsequent calls with the same UUID return the exact same Python object, not a copy. If the object cannot be found, an exception is raised.
Examples
Fetch an object by its UUID
The most common use case is retrieving an object using its unique ID.
# Create an object and get its UUID
obj_1 = MemoTestClass(value=123)
obj_uuid = db0.uuid(obj_1)
# Fetch the same object using its UUID
obj_2 = db0.fetch(obj_uuid)
# obj_1 and obj_2 are the exact same instance in memory
assert obj_1 is obj_2Fetch a singleton instance by its type
For singleton classes, you can fetch the unique instance just by providing the class type.
# Create a singleton instance
singleton_1 = MemoTestSingleton(value=999)
# Fetch the singleton instance using its class
singleton_2 = db0.fetch(MemoTestSingleton)
assert singleton_1 is singleton_2Fetch with type validation
You can ensure the fetched object is of an expected type by passing a second argument.
obj = MemoTestClass(value=123)
obj_uuid = db0.uuid(obj)
# This will succeed
retrieved_obj = db0.fetch(obj_uuid, MemoTestClass)
assert retrieved_obj.value == 123
# This will raise an exception because the type does not match
with pytest.raises(Exception):
db0.fetch(obj_uuid, DynamicDataClass)Fetch a singleton from a specific prefix
If you're working with multiple data prefixes, you can specify which one to fetch a singleton from.
# Create a singleton on the current prefix
px1 = db0.get_current_prefix().name
_ = MemoTestSingleton(value=123)
# Switch to another prefix and create another singleton of the same type
db0.open("my-other-prefix", "rw")
_ = MemoTestSingleton(value=456)
# Fetch the specific singleton from each prefix
obj_px1 = db0.fetch(MemoTestSingleton, prefix=px1)
obj_px2 = db0.fetch(MemoTestSingleton, prefix="my-other-prefix")
assert obj_px1.value == 123
assert obj_px2.value == 456