Valkey Python Client
Valkey-py is a high-performance Python client for Valkey, a robust open-source (BSD) key/value datastore. Forked from redis-py, it supports a variety of workloads including caching, message queues, and acting as a primary database. The library is actively maintained with frequent releases, including release candidates for upcoming versions.
Warnings
- breaking Starting with `v6.1.0b1`, Valkey-py removed expiration/TTL commands not supported by Valkey (diverging from Redis behavior). Verify if your application relies on specific TTL commands that might have been dropped.
- breaking Python version support has changed. `v6.1.1` dropped Python 3.8 support, and `v6.2.0rc1` (future stable `6.2.0`) dropped Python 3.9 support. Valkey-py now officially requires Python 3.10 or newer.
- gotcha Valkey-py is a fork of `redis-py`. While highly compatible with Redis 7.2, Valkey and Redis are separate projects with independent roadmaps. Expect potential future divergence in features, commands, and API behaviors.
- gotcha By default, Valkey-py returns responses as bytes. To receive decoded strings, you must explicitly pass `decode_responses=True` to the `Valkey` or `from_url` constructor.
- gotcha When using `valkey.asyncio` clients, explicit disconnection via `await client.aclose()` is required to properly close connections and internal connection pools, especially if you create custom `ConnectionPool` instances.
- gotcha For Pub/Sub features, if `health_check_interval` is set (e.g., in a `from_url` connection), you must call `get_message()` or `listen()` (or `check_health()`) frequently enough to avoid connection timeouts. Failure to do so can lead to connection closure by the server.
Install
-
pip install valkey -
pip install "valkey[libvalkey]"
Imports
- Valkey
from valkey import Valkey
- Redis
from valkey import Redis
Quickstart
import valkey
import os
def main():
# Connect to Valkey (defaults to localhost:6379)
# Use VALKEY_URL environment variable for production configurations
valkey_url = os.environ.get('VALKEY_URL', 'valkey://localhost:6379')
r = valkey.from_url(valkey_url, decode_responses=True)
try:
r.ping()
print(f"Connected to Valkey at {valkey_url}")
# Set a key-value pair
r.set('mykey', 'Hello, Valkey!')
print("Set 'mykey' to 'Hello, Valkey!'")
# Get the value back
value = r.get('mykey')
print(f"Value of 'mykey': {value}")
except valkey.exceptions.ConnectionError as e:
print(f"Could not connect to Valkey: {e}")
finally:
# For async clients, explicitly await aclose()
# For sync clients, connection is managed by pool
pass
if __name__ == '__main__':
main()