Because the cycle() method is recursive, but when you call it recursively, you are not returning the result returned by the recursive call.
So, inside self.cycle() , let's say you call self.cycle() again, and then when you try to call self.cycle() , a RuntimeError occurs, so the call returns 10 back to the first call to self.cycle() , but this one (say, the first self.cycle() ) call does not return this result back to the caller, so the result returned by the second self.cycle() is lost, and you return None .
If you return the result of calling self.cycle() , you should get the correct result. Example -
>>> import sys >>> sys.setrecursionlimit(3) >>> class Test: ... def cycle(self, n=float("inf"), block="x"): ... try: ... return self.cycle(n-1, block) ... except RuntimeError as e: ... if str(e) == "maximum recursion depth exceeded": ... print("... forever") ... return 10 ... >>> t = Test() >>> print(t.cycle()) ... forever 10
Please note: I set the recursion limit to 3 so that the recursion depth exceeds the error after three recursion levels.
source share