10

I'm trying to store a custom, serializable python object in Redis, but have encountered some strange behavior. The set method seems to function, but the get method only returns the value of the object's __repr__ method. For instance...

import redis

# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)

# define a custom class
class SomeCustomObject(object):
    pass

When I try to set the SomeCustomObject as a value, it appears to work:

>>> rs.set('c', SomeCustomObject())
True

However, when I get the value back, it's just the __repr__ string:

>>> rs.get('c')
'<__main__.SomeCustomObject object at 0x102496710>'

How do I store/get the instance back? I've not had much luck finding any info on this in the documentation, but surely I'm not the first one to encounter this?

1
  • Where are you serializing the object? Commented Apr 7, 2017 at 17:08

1 Answer 1

21

Use Pickle

Using the pickle module you can serialize and deserialize Python objects and pass them to Redis.

From this so answer - https://stackoverflow.com/a/20400288/4403600, it would look like this:

import pickle
import redis

# define a custom class
class SomeCustomObject(object):
    pass

# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)

# pickle and set in redis
rs.set('c', pickle.dumps(SomeCustomObject()))

# get from redis and unpickle
unpacked_object = pickle.loads(rs.get('c'))

Further reading - https://docs.python.org/2/library/pickle.html

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, this is great. I was (for whatever misguided reason) under the impression redis-py would handle the pickling, so long as I had the __getstate__, __setstate__ pieces handled. Thank you!
This works! thank you so much

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.