I was just playing around with a python function that changes itself and couldn't avoid infinite recursion. At some point I made this:
def mitsos(a):
global mitsos
def takis(f):
def w(*args, **kargs):
ret = f(*args, **kargs)
return ret + 1
return w
mitsos = takis(mitsos)
return a
This unexpectedly worked. If i call mitsos(1) multiple times the result is always by 1 higher than the previous result. Why doesn't it fall in infinite recursion though?
Your original function is not recursive at all, less infinitely recursive. Function
mitsos
creates another functiontakis
. Then it calls that function. The functiontakis
creates another functionw
and returns it. The new function becomes the value ofmitsos
, and the originalmitsos
returns. Period.The redefined function is one step-recursive, and it redefines
mitsos
again. The newmitsos
is two-step recursive, etc. But none of them is infinitely recursive.