openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Refactor openlibrary.core.cache get function

Open dherbst opened this issue 5 years ago • 2 comments

In https://github.com/internetarchive/openlibrary/pull/4296#discussion_r557523924 The class MemcacheCache(Cache) get function: https://github.com/internetarchive/openlibrary/blob/master/openlibrary/core/cache.py#L312-L317

    def get(self, key):
        key = web.safestr(key)
        stats.begin("memcache.get", key=key)
        value = self.memcache.get(key)
        stats.end(hit=value is not None)
        return value and simplejson.loads(value)

@cclauss says:

I do not love this approach for a return statement because we (and the caller) are clueless about what the return type is going to be... If value is '' then we return a str, if If value is 0 then we return an int, If value is 0.0 then we return a float, If value is {} then we return a dict, etc.

What about return value and json.loads(value) or {} (we always return a dict) or return value and json.loads(value) or None (we return an Optional[dict])?

I suggested opening this issue instead of solving this refactor in that pull request because the memcache get function is used in quite a few places and changing the return value needs to be well tested.

Stakeholders

@cclauss @dherbst

dherbst avatar Jan 14 '21 20:01 dherbst

Related to #7312

mekarpeles avatar Sep 15 '23 19:09 mekarpeles

Hi, can I work on this?

MemcacheCache.get in openlibrary/core/cache.py still has return value and json.loads(value). Since set() always saves json.dumps(...), the stored value is never an empty string. So changing it to

return json.loads(value) if value is not None else None

doesn't change how it works. It just makes it clear that it returns the cached value, or None if nothing is cached. Values in the cache aren't always dicts, so I think returning None on a miss is safer than always returning {}.

I'll check the places that call it and add tests for cached values like 0, [] and {}. @scottbarnes

Animesh-Jantwal avatar Oct 29 '26 09:10 Animesh-Jantwal