Self function

Emile van Sebille emile at fenx.com
Sun May 3 20:21:53 EDT 2009


On 5/3/2009 3:39 PM bearophileHUGS at lycos.com said...
> Sometimes I rename recursive functions, or I duplicate&modify them,
> and they stop working because inside them there's one or more copy of
> their old name.
> This happens to me more than one time every year.
> So I have written this:
> 
> from inspect import getframeinfo, currentframe
> 
> def SOMEVERYUGLYNAME(n):
>     if n <= 1:
>         return 1
>     else:
>         self_name = getframeinfo(currentframe()).function
>         #self_name = getframeinfo(currentframe())[2] # older python
> 
>         # only if it's a global function
>         #return n * globals()[self_name](n - 1)
>         return n * eval(self_name + "(%d)" % (n - 1))
> assert SOMEVERYUGLYNAME(6) == 2*3*4*5*6
> 
> Are there nicer ways to do that? 

I've sometimes used classes like:


class SOMEVERYUGLYNAME:
     def __call__(self,n):
         if n<=1:
             return 1
         else:
             return n*self.__class__()(n-1)

assert SOMEVERYUGLYNAME()(6) == 2*3*4*5*6


It's probably nicer (for some definition of nice), but I wouldn't say 
it's nice.

Emile




More information about the Python-list mailing list