pythonmemcachedpython-memcached

Python: Add compiled object to Memcached


I try to add a compiled object to Memcached that is regularly used. The compiled object does never change.

cache.set(eq, compile(eq, '<string>', 'eval'), 365*24*60*60)

But get the following error message:

Can't pickle < class 'code' >: attribute lookup code on builtins failed

Is there any solution to this problem or an alternative approach?


Solution

  • You can use marshal module which is specifically designed for internal object serialization

    cache.set(eq, marshal.dumps(compile(eq, '<string>', 'eval')), 365*24*60)
      ...
    eval(marshal.loads(cache.get(eq)))
    

    alternatively you can store the source

    cache.set(eq, eq, 365*24*60)
       ...
    eval(cache.get(eq))
    

    Either way you may need to evaluate potential security risks of executing code retrieved from external cache.