How to test for an an empty Redis key in python
Asked Answered
L

2

18

I am using redis-py (https://redis-py.readthedocs.org/en/latest/).

lets say I have some redis keys saved and av. 'av' has no assigned value so using the command line, I can do:

>>> redis.get('saved')
Out[4]: 'None'
>>> redis.get('av')
>>> redis.get('saved')
Out[6]: 'None'

How would you test for 'no assigned value' for a key in this context?

Luxate answered 7/7, 2015 at 17:8 Comment(4)
Is if redis.get('av'):` not working?Horseradish
I'm not sure I follow. Does 'redis.get('av')' evaluate to False?Luxate
Check the command EXISTS in Redis.Yee
@user61629 It looks like if it doesn't find the key it returns None, which would be in line with how get() works for dicts (this get() is probably inherited from dict). Run this and see what it says: redis.get('av') is NoneHorseradish
V
38

You should use the method exists, which returns a boolean - True if your key is set, False otherwise. You should avoid the use of get for that, as it can raise an exception if you have a list value for that key.

Example:

>>> redis.exists("av")
False
Visor answered 17/8, 2018 at 15:59 Comment(2)
With redis v3.0, it no longer returns a boolean. It now returns the number of keys that were found in the db, as you can now pass multiple keys to exists. As 0 is falsey in python, most code should still work, but it is good to know about this change.Susurrus
Exceptions are clearer, the fact that something raises an exception is not an issue and can in fact be desired.Mandibular
D
0

Keep in mind that the time complexity for EXISTS is O(N), whereas for GET it is O(1). This could make a bit of difference for large datasets. So, a better approach might be to check for None, as such:

existingEntry = redis.get('av')
if existingEntry:
    # entry exists
else:
    # entry does not exist
Debag answered 9/8 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.