why memoizing is faster

eryksun () eryksun at gmail.com
Fri Mar 25 06:04:17 EDT 2011


On Thursday, March 24, 2011 8:12:22 PM UTC-4, Terry Reedy wrote:
>
> If Python did what some have asked, which is to make 'recursive' 
> functions actually recursive by replacing a local variable that matches 
> the function name (in this 'fib') with a direct reference to the 
> function itself, as a constant (and this could be done), then the 
> wrapper would not get called from within the function.

Regarding this I have question about function attributes. Is there an equivalent of 'self' for functions? I've seen people use function attributes as local static variables, but this seems problematic when all you have is a global reference to the function. The original reference might get deleted. Then when your function tries to reference its 'static' variable you'll get a NameError exception. For example:

In [1]: def test1(n):
   ...:     test1.a = n

In [2]: test1(10); test1.a
Out[2]: 10

In [3]: test2 = test1; test2.a
Out[3]: 10

In [4]: del test1

In [5]: test2(20); test2.a
-------------------------------
NameError        


Should such a function always take a reference to itself as the first parameter?              

In [6]: def test1(f, n):
   ...:     f.a = n

In [7]: test1(test1, 10); test1.a
Out[7]: 10

In [8]: test2 = test1; test2.a
Out[8]: 10

In [9]: del test1

In [10]: test2(test2, 20); test2.a
Out[10]: 20

Granted, this would be better handled in a class.



More information about the Python-list mailing list