Self function

Steve Howell showell30 at yahoo.com
Mon May 4 02:21:10 EDT 2009


On May 3, 5:21 pm, Emile van Sebille <em... at fenx.com> wrote:
> On 5/3/2009 3:39 PM bearophileH... 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.
>

Some of that could probably abstracted into a decorator maybe?



More information about the Python-list mailing list