Async Key-Value Store - Pluggable Interface
py-key-value-aio is an asynchronous Python library offering a pluggable interface for various Key-Value (KV) stores. It provides a backend-agnostic abstraction layer, allowing framework authors and applications to integrate KV storage without committing to a specific implementation like Redis, DynamoDB, or an in-memory solution. The library, currently at version 0.4.4, focuses exclusively on async/await patterns and requires Python >=3.10. It is actively maintained as part of a larger monorepo.
Warnings
- breaking This library is strictly async-only. A synchronous wrapper is not planned, so ensure your application uses `async/await` patterns consistently when integrating `py-key-value-aio`.
- gotcha Values retrieved from the store are 'managed entries' (often JSON-serialized) and are copies, not 'live' objects. Modifying the retrieved dictionary or Pydantic model will not affect the stored value until you explicitly `put` it back. The library ensures type safety but does not return the same in-memory instance.
- gotcha The library utilizes `beartype` for runtime type checking on core protocol methods. Violations will raise `TypeError`. This can be unexpected if not accounted for during development or if data types are inconsistent.
- gotcha While `py-key-value-aio` provides many backend integrations, their maturity and specific limitations may vary. Relying on certain backends in production without thorough review of their specific documentation and caveats within the `py-key-value` monorepo can lead to unexpected behavior.
Install
-
pip install py-key-value-aio -
pip install py-key-value-aio[memory] -
pip install py-key-value-aio[redis]
Imports
- AsyncKeyValue
from key_value.aio.protocols.key_value import AsyncKeyValue
- MemoryStore
from key_value.aio.stores.memory import MemoryStore
Quickstart
import asyncio
from key_value.aio.protocols.key_value import AsyncKeyValue
from key_value.aio.stores.memory import MemoryStore
async def example_usage(key_value_store: AsyncKeyValue):
print(f"Putting key 'user:123' with value {{'name': 'Alice'}}")
await key_value_store.put(key="user:123", value={"name": "Alice"}, collection="users", ttl=3600)
print("Retrieving 'user:123'...")
user_data = await key_value_store.get(key="user:123", collection="users")
print(f"Retrieved: {user_data}")
print("Deleting 'user:123'...")
await key_value_store.delete(key="user:123", collection="users")
print("Attempting to retrieve 'user:123' again...")
deleted_user_data = await key_value_store.get(key="user:123", collection="users")
print(f"Retrieved after deletion: {deleted_user_data}") # Should be None
async def main():
# Example with MemoryStore
memory_store = MemoryStore()
await example_usage(memory_store)
if __name__ == '__main__':
asyncio.run(main())