Self function

Steve Howell showell30 at yahoo.com
Mon May 4 11:27:06 EDT 2009


On May 3, 3:39 pm, bearophileH... at lycos.com wrote:
> 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 don't know.
> If there aren't, then a way may be added.
> An idea-syntax:
>
> def fact(n):
>     return 1 if n <= 1 else n * inspect.self(n - 1)
>
> Or even a lambda, because you don't need the name anymore to call the
> function:
>
> fact = lambda n: 1 if n <= 1 else n * self(n - 1)
>
> (If you have two or more recursive functions that call each other this
> idea can't be used, but I think such situations are uncommon enough to
> not deserve help from the language).
>

One very simple thing that you can do is assign the current function
name to a local var at the very top to make it a little more obvious.

I agree that there are lots of recursive patterns where python itself
does not provide much sugar.  A pattern that comes up for me
occasionally is two methods with almost identical names, where one
function is the public interface and then another method that does
most of the recursion.



More information about the Python-list mailing list