Python LevelDB Bindings (Unmaintained)
This package provides Python bindings for the LevelDB key-value store. It allows Python applications to interact with LevelDB databases for embedded, persistent key-value storage. Note: This specific PyPI package (`leveldb`) is largely unmaintained (last release 2017). Version 0.201. Releases are infrequent to non-existent.
Warnings
- breaking This `leveldb` PyPI package is unmaintained (last release 2017) and is known to have compatibility issues with newer Python versions and operating systems. For active development and better support, consider using `plyvel` (https://pypi.org/project/plyvel/), which is an actively maintained alternative.
- gotcha Keys and values *must* be `bytes`. Attempting to use `str` will result in a `TypeError` or unexpected behavior.
- gotcha Retrieving a non-existent key with `db.Get(key)` will raise a `KeyError`, not return `None`.
- gotcha Only one process can open a LevelDB database at a time for writes. Attempting to open an already-locked database for writing will result in an error or hang, typically `leveldb.Error`.
- gotcha Requires the C++ LevelDB library to be installed on the system *before* `pip install leveldb`. Without it, installation will fail with compilation errors.
Install
-
pip install leveldb
Imports
- LevelDB
import leveldb db = leveldb.LevelDB('./path/to/db')
Quickstart
import leveldb
import os
import shutil
# Define a temporary database path
db_path = './my_temp_leveldb'
# Ensure clean slate for demonstration
if os.path.exists(db_path):
shutil.rmtree(db_path)
try:
# Open the database, creating it if it doesn't exist
# Note: create_if_missing is implicitly True by default
db = leveldb.LevelDB(db_path)
print(f"Database opened at {db_path}")
# Put a key-value pair (keys and values must be bytes)
db.Put(b'name', b'Alice')
db.Put(b'age', b'30')
print("Put: name -> Alice, age -> 30")
# Get a value
name = db.Get(b'name')
print(f"Get 'name': {name.decode('utf-8')}")
# Iterate through keys
print("All keys in DB:")
for key, value in db.RangeIter():
print(f" {key.decode('utf-8')}: {value.decode('utf-8')}")
# Try to get a non-existent key (raises KeyError)
try:
db.Get(b'city')
except KeyError:
print("Successfully caught KeyError for non-existent key 'city'")
finally:
# Clean up the database directory
if os.path.exists(db_path):
shutil.rmtree(db_path)
print(f"Cleaned up database at {db_path}")