Function decorator that caches function results

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Oct 9 07:27:37 EDT 2005


On Sun, 09 Oct 2005 02:49:38 -0700, Paul Rubin wrote:

>> I'm curious... where does cache live after you use cache_function to
>> memoize some function? It doesn't appear to be an attribute of the newly
>> memoized function, nor does it look like a global variable.
> 
> It's in the closure returned by cache_function.

What's a closure?

Googling on define:closure isn't very useful. There are a *lot* of
different meanings for closure, none of them to do with programming.

No, wait, I tell a lie -- Wikipedia to the rescue again:

http://en.wikipedia.org/wiki/Closure_(programming)

I notice that type(some_closure) and type(ordinary_function) both return
the same result, <type 'function'>. I also notice that both the closure
and ordinary functions have an attribute "func_closure". Is there a way to
tell which is a closure and which is not? In my tests, the ordinary
function has func_closure == None, but I don't know if that will always be
the case of just for my tests.

If I wanted to inspect the value of cache, where would I find it? In other
words, if I say some_closure.SOMETHING I would get cache... what should
SOMETHING be set to?

That assumes that cache can be seen in this way. If it can't, is this a
way to create "really private" variables in Python?



-- 
Steven.




More information about the Python-list mailing list