dbzero.set(iterable=None)
Creates a persistent, mutable, and unordered collection of unique elements, analogous to Python's built-in set.
Parameters
iterable(optional): An iterable (e.g., alist,tuple, or anotherset) used to initialize thedbzero.set. If not provided, an empty set is created.
Returns
A new dbzero.set object. This object mirrors the interface of Python's native set, supporting all standard methods (.add(), .remove(), .union(), etc.) and operators (|, &, -, ^).
Description
The dbzero.set() factory function provides a set data structure that is fully managed and persisted by dbzero. It behaves just like a regular Python set but with the added benefit of automatic persistence and caching.
Key Features:
- Persistence: Any modifications to the set, such as adding or removing elements, are saved to the database upon
dbzero.commit(). - Interoperability:
dbzero.setobjects can be seamlessly used in operations with standard Pythonsets. - Reference Management: When you add a
@dbzero.memodecorated object to adbzero.set,dbzerotracks this relationship. If the object is later removed from the set (or the set itself is deleted),dbzeroautomatically handles its garbage collection during the next commit cycle, provided no other references to the object exist.
Examples
Creating and Modifying a Set
You can create an empty set and add items, or initialize it from a list.
# Create an empty db0.set
users = db0.set()
# Add elements
users.add("alice")
users.add("bob")
users.add("charlie")
users.add("alice") # Duplicates are ignored
print(len(users))
# Expected output: 3
print("bob" in users)
# Expected output: TrueInitializing from an Iterable
Create a dbzero.set directly from a list.
initial_data = [1, 2, 3, 4, 5, 1, 2]
my_numbers = db0.set(initial_data)
print(my_numbers)
# Expected output (order may vary): {1, 2, 3, 4, 5}Set Operations
dbzero.set supports all standard set operations, like union, intersection, and difference, even with native Python sets.
# A persistent set of approved users
approved_users = db0.set(["eva", "frank", "grace"])
# A standard Python set of new applicants
new_applicants = {"grace", "heidi", "ivan"}
# Get all unique users
all_users = approved_users.union(new_applicants)
print(all_users)
# Expected output (order may vary): {'frank', 'ivan', 'eva', 'grace', 'heidi'}
# Get users who are both approved and new applicants
overlapping_users = approved_users.intersection(new_applicants)
# You can also use the '&' operator
# overlapping_users = approved_users & new_applicants
print(overlapping_users)
# Expected output: {'grace'}