Take the 2-minute tour ×

I'm working with xlwt which has a 4k limit on how many styles can be defined in an excel doc.

Normally, one creates styles like so:

style = xlwt.easyxf("font: bold 1")

Which I simply replaced with

def cached_easyxf(self, format):
    return self._cache.setdefault(format, xlwt.easyxf(format))

Which works perfectly. Now, I've found out that I need to pass in keyword arguments sometimes which got me thinking: how should I hash the args/kwargs signature?

Should I create a cache key based on str(value)? Pickle? What's most robust?

For my situation it looks like I can just convert key/values to strings and add it to my keys... but I'm now curious about a generic way to handle this with say unhashable types like arg=[1, 2, 3]

def cached_call(*args, **kwargs):
    return cache.get(what_here)
cached_call([1, 2, 3], {'1': True})
share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

Here is the technique used in functools.lru_cache():

kwd_mark = object()     # sentinel for separating args from kwargs

def cached_call(*args, **kwargs):
    key = args + (kwd_mark,) + tuple(sorted(kwds.items()))
    return cache.get(key)

Note, that code handles keyword arguments but makes no attempt to handle non-hashable values like lists. You're idea for using the str of a list is a reasonable start. For set objects, you would need to sort the entries first, str(sorted(someset)). Other objects may not have a useful repr or str (i.e. they may show only the object type and location in memory). Summary, handling arbitrary unhashable arguments requires careful consideration of each object type.

share|improve this answer
Thanks for the answer Raymond! Much appreciated –  Yuji 'Tomita' Tomita Apr 19 '12 at 17:33
Would the following work just as well: key = (args, tuple(sorted(kwds.items())))? Or is it slower because of inner tuples? –  max Sep 20 '12 at 11:41
@max Yes, that would work. And yes, the extra pointers would slow it down a bit as well as consuming a bit more memory. –  Raymond Hettinger Sep 20 '12 at 22:10
add comment

Your Answer


