This is specifically related to the Google App Engine Memcache API, but I’m sure it also applies to other Memcache tools.
The dictionary .get() method allows you to specify a default value, such as dict.get(‘key’, ‘defaultval’)
This can be useful if it’s possible you might want to store None as a value in a dictionary.
However, the memcache.get() does not let you to do this. I’ve modified my @memoize decorator so it looks like this:
def memoize(keyformat, time=1000000):
"""Decorator to memoize functions using memcache."""
def decorator(fxn):
def wrapper(*args, **kwargs):
key = keyformat + str(args[1:]) + str(kwargs)
from google.appengine.api import memcache
data = memcache.get(key)
if Debug(): return fxn(*args, **kwargs)
if data:
if data is 'None': data = None
return data
data = fxn(*args, **kwargs)
if data is None: data = 'None'
memcache.set(key, data, time)
return data
return wrapper
return decorator
Now I’m sure there’s a good argument that I shouldn’t be storing None values in the first place, but let’s put that aside for now. Is there a better way I can handle this besides converting None vals to strings and back?
A possible way to do this is to create new class that defines
Nonefor this purpose, and assign instances of this to the cache (unfortunately you cannot extendNone). Alternatively, you could use the empty string “”, or avoid storing None/null values altogether (absence of the key implies None).Then check for instances of your ‘None’ class when you check the result of
mc.get(key)(is None,== "", etc)