This guide walks you through creating, loading, manipulating, and persisting data with BinaryDB. By the end, you’ll understand the complete lifecycle of working with a BinaryDB database.
1
Import the Database class
Start by importing the Database class from the binarydb package:
from binarydb.database import Database
This is the main class you’ll interact with. It provides all the methods for storing, retrieving, and managing your data.
2
Create a database instance
Create a database instance by specifying a file path:
db = Database("./data/mydb")
This creates a database that will be stored at ./data/mydb.pkl. The .pkl extension is added automatically.
The database file won’t be created until you call commit(). If the directory doesn’t exist, you’ll need to create it first:
import osos.makedirs("./data", exist_ok=True)
3
Load existing data (if any)
If a database file already exists at the path, load it:
db.load()
This reads the database from disk and loads all records into memory. If the file doesn’t exist, this method does nothing—your database will simply start empty.
Always call load() before working with a database that might already contain data. Otherwise, you’ll start with an empty database and overwrite existing data when you commit.
4
Store data with set()
Add records to your database using the set() method:
# Store a dictionarydb.set("user:1", {"name": "Ana", "age": 30})# Store different data typesdb.set("config", {"theme": "dark", "language": "en"})db.set("counter", 42)db.set("tags", ["python", "database", "tutorial"])
You can store any pickle-serializable Python object: dictionaries, lists, numbers, strings, custom objects, etc.Expected output:
(No output - data is stored in memory)
5
Retrieve data with get()
Fetch records by their key:
user = db.get("user:1")print(user)# Output: {'name': 'Ana', 'age': 30}# Provide a default value if the key doesn't existtheme = db.get("theme", default="light")print(theme)# Output: light
The get() method works just like dictionary access but with an optional default value.
6
Update dictionary records
For records that are dictionaries, use update() to modify specific fields:
# Update specific fieldsdb.update("user:1", {"age": 31, "city": "Madrid"})# Check the resultprint(db.get("user:1"))# Output: {'name': 'Ana', 'age': 31, 'city': 'Madrid'}
The update() method only works with dictionary records. If you try to update a non-dictionary value, you’ll get a RecordTypeError.
7
Check existence and delete records
Use exists() to check if a key is present, and delete() to remove records:
# Check if a key existsif db.exists("user:1"): print("User 1 exists")# Delete a recorddb.delete("counter")# Verify deletionprint(db.exists("counter"))# Output: False
8
Persist changes with commit()
Save all changes to disk:
db.commit()
This writes the entire database to disk atomically using a temporary file, preventing corruption if the write fails.
Changes are only stored in memory until you call commit(). If your program crashes before committing, unsaved changes will be lost.
9
Close the database
When you’re done, close the database:
db.close()
This commits any pending changes and marks the database as closed. After closing, you can’t perform any more operations on this instance.
Create a simple context manager for automatic cleanup:
from contextlib import contextmanager@contextmanagerdef open_database(path): db = Database(path) db.load() try: yield db finally: db.close()# Use itwith open_database("./data/mydb") as db: db.set("key", "value") print(db.get("key"))# Database is automatically closed
# User recordsdb.set("user:1", {...})db.set("user:2", {...})# Configurationdb.set("config:app", {...})db.set("config:db", {...})# Sessionsdb.set("session:abc123", {...})# Get all usersall_data = db.all()users = {k: v for k, v in all_data.items() if k.startswith("user:")}
Call load() before working with a database to ensure you have the latest data from disk.
Commit regularly
Call commit() after important changes to prevent data loss if your program crashes.
Use transactions
Wrap related operations in transactions with begin() and end() for atomicity.
Close when done
Always call close() when finished to ensure pending changes are saved.
Memory considerations: All data is kept in memory. For large datasets, monitor your memory usage and consider alternative solutions if your data doesn’t fit comfortably in RAM.