1

So I'm using @lru_cache on my objects in different parts, and I'm just wondering how to flush the cache on all functions on an object where @lru_cache is used, something like:

for i in dir(self):
  if 'cache_clear' in dir(i):
    self.get_attr(i).cache_clear()

The problem is:

  • I'm not sure if this is really a very elegant way to do it
  • cache_clear doesn't actually appear when I do dir() on the function which it decorates

What's the best way to do this?

cjm2671
  • 18,348
  • 31
  • 102
  • 161

1 Answers1

2

When you request an instance method from self, Python returns a bound method object that does not have the cache_clear method.

You need to avoid triggering instance method lookup:

for value in vars(self).values():
    attr = getattr(value, 'cache_clear', None)
    if callable(attr):
        attr()

Keep in mind that @lru_cache cache is shared among instances of the class, which means that calling cache_clear from within one instance will empty the cache for all instances (possible solution).

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Just on the last point, if I have separate objects, they share a cache? Surely the data won't get confused, as 'self' is passed every time? – cjm2671 Aug 16 '16 at 08:34
  • 1
    @cjm2671 yes, the cache is shared. Calling `cache_clear` within one of the instances will clear it for all instances. There're solutions to this, though http://stackoverflow.com/a/14946506/2301450 – vaultah Aug 16 '16 at 08:37