vivekn / redis-simple-cache

Simple redis based cache for storing results of python function calls, json encoded strings or html.
Other
122 stars 69 forks source link

Allow cache_it* decorators to provide a way to cache instance methods #24

Open SantjagoCorkez opened 10 years ago

SantjagoCorkez commented 10 years ago

That'd be a good option to have cache_it() and cache_it_json() either auto-detecting instance methods or being marked of such a use case by, for example, strip_first_arg boolean parameter that'd perform something like

pickle.dumps(args[1:])

There's a side effect in such a use case, I know, but could be an option for those who know what they do.

In my case, using instance methods eliminates a need to call getLogger every time I need to log something and provides an option to use one, instance-wide, logger (which certainly cannot be pickled because of file descriptors inside any logger object).

fjsj commented 10 years ago

Hi SantjagoCorkez,

I think you can't just strip self out from the cache_key, since different instances probably will return different values even for the same method. I believe this is the default use case.

Probably in your case you need something different from this, so I think you can create your own decorator around cache_it decorator. If you need help for doing this, please let me know.

SantjagoCorkez commented 10 years ago

Well, in my case the solution just strips out the first function arg. No matter what is it: self, cls or any generic argument as in staticmethod. And this guarantees no side effects in my case, because instance's self contains no information that could cause difference between instance of class A(B) and class C(B), where B inits only logger.

As I've said, that could be specially marked in documentation as 'think twice when you use this argument'.

As for more generic solution this could be also implemented as strip_args=0 argument for decorator and pickle.dumps(args[strip_args:]) in code. That could help when one needs to exclude some N-first args of a function from cache entry's hash key.