locked()
The dbzero.locked() method is a versatile context manager designed for grouping operations. It serves two primary functions: synchronously analyzing which data prefixes are mutated by a block of code, and asynchronously waiting for those mutations to be fully committed.
Parameters
| Name | Type | Description |
|---|---|---|
await_commit | bool | (Optional) If True, the context manager becomes asynchronous (async with) and execution will pause until any autocommits triggered within the block are complete. Defaults to False. |
Usage and Examples
You can use locked() in two ways depending on your needs.
Synchronous Analysis
When used as a standard with statement, locked() helps you see the "blast radius" of your code. It tracks all object mutations and yields a lock object. After the with block finishes, you can call lock.get_mutation_log() to get a report of which data prefixes were modified.
This is great for debugging or for building logic that reacts to data changes. The log only records actual mutations; read-only operations are ignored.
# Create some objects in different prefixes
obj_1 = MemoTestClass(951)
db0.open("some-new-prefix", "rw")
obj_2 = MemoTestClass(952)
# Use locked() to track changes
with db0.locked() as lock:
# A read operation does not create a log entry
x = obj_1.value
# A mutating operation does
obj_2.value = 123123
# After the block, get the mutation log
mutation_log = lock.get_mutation_log()
# The log shows that only "some-new-prefix" was modified
assert len(mutation_log) == 1
assert mutation_log[0][0] == "some-new-prefix"
print(mutation_log)
# Output: [('some-new-prefix', 1)]