Function decorator that caches function results

Diez B. Roggisch deets at nospam.web.de
Sun Oct 9 08:04:39 EDT 2005


> If you create a closure, using a memoization technique as per the original
> post, and then call type() on that closure, Python reports <type 'function'>. 

Because it is. The closure is only sort of an extension to the locals() 
available to that function. Not more, not less.
> 
> If you use dir() on that closure-that-Python-calls-a-function, it tells
> you that there is an attribute "func_closure". But ordinary functions that
> aren't closures also have that attribute.

Because there is no difference between them - a function _can_ have a 
closure, the same way a HttpRequest _can_ have POST-data or not. That 
doesn't make it different.

You are of course right that one _could_ have implemented this with 
different classes. But as it happens, it isn't.

> 
> According to my tests, ordinary functions have None as the func_closure
> attribute, but I don't know if that will always be the case, or just the
> few examples I tested it. With a sample size of three, I have no
> confidence that I've found a bullet-proof test.

See this small testscript how to expose the closures content -- however 
I'm not familiar with the mechanics the bind "some_variable" to the 
cell-objects content. But actually I don't care...

def closure_test():
     some_variable = {}
     print "%x" % id(some_variable)
     def get(x):
	return some_variable[x]
     def set(x,v):
	some_variable[x] = v
     return get, set



g, s = closure_test()

s(10, 20)
print g(10)
print s.func_closure[0]

Diez



More information about the Python-list mailing list