Python infinite recursion

438 Views Asked by At

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?

1

There are 1 best solutions below

6
On

Your original function is not recursive at all, less infinitely recursive. Function mitsos creates another function takis. Then it calls that function. The function takis creates another function w and returns it. The new function becomes the value of mitsos, and the original mitsos returns. Period.

The redefined function is one step-recursive, and it redefines mitsos again. The new mitsos is two-step recursive, etc. But none of them is infinitely recursive.