# Self function

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat May 9 02:41:08 CEST 2009

```On Thu, 07 May 2009 08:21:51 -0700, Francis Carr wrote:

> In the special case of a self-recursive function, you would like re-
> naming "to just work".  Out of morbid curiosity, I am compelled to
> ask... why do you expect that re-naming anything --- a function, a
> class, a module, a variable, anything --- in just one place but not all
> the others should ever, under any circumstances, "just work" ?

Patching functions to do pre-processing or post-processing can be a
useful technique, (e.g. for tracing and debugging). This works for
regular functions, but not recursive functions.

>>> def listify(x):
...     return [x]
...
>>> listify(42)
[42]
>>>
>>> _old_listify = listify
>>> def listify(x):
...     print "Calling listify"
...     return _old_listify(x)
...
>>> listify(42)
Calling listify
[42]

Note that the call to listify "just works" -- the patch runs once, the
original version of the function runs once, and we get the expected
results without any problems.

Now try the same technique on a recursive function, and it fails:

>>> def rec(x):
...     if x > 0: return [x] + rec(x-1)
...     else: return []
...
>>> rec(5)
[5, 4, 3, 2, 1]
>>>
>>> _old_rec = rec
>>> def rec(x):
...     print "Calling rec"
...     return _old_rec(x)
...
>>> rec(5)
Calling rec
Calling rec
Calling rec
Calling rec
Calling rec
Calling rec
[5, 4, 3, 2, 1]

Note too that if you're given an arbitrary function, there's no simple
way of telling whether it's recursive or not. Properly written "self-
reflective" functions using my proposed technique should be immune to
this problem.

--
Steven

```