19

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?

4
  • Is if redis.get('av'):` not working? Commented Jul 7, 2015 at 17:21
  • I'm not sure I follow. Does 'redis.get('av')' evaluate to False? Commented Jul 7, 2015 at 17:41
  • 2
    Check the command EXISTS in Redis. Commented Jul 7, 2015 at 19:47
  • 1
    @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 None Commented Jul 7, 2015 at 20:32

1 Answer 1

40

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Exceptions are clearer, the fact that something raises an exception is not an issue and can in fact be desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.