Python break deep recursion - 2.7.8
Question: So I have a huge recursive function. At some point, it finds a result, and I
need it to stop all functions. Suggestions?


Answer: Assuming you cannot refactor your code, you could use generators to achieve
this. Let's say we have the following code:

    
    
    from __future__ import print_function
    
    def g(n):
        print("g before", n)
        if n < 3:
            for i in g(n+1):
                yield i
        else:
            yield n
        print("g after", n)
    

The normal execution would be:

    
    
    >> for i in g(0):
    ...     print(i)
    ...
    g before 0
    g before 1
    g before 2
    g before 3
    3
    g after 3
    g after 2
    g after 1
    g after 0
    

Now what you want is to yield 3 and stop right there, so we just fetch the
first value:

    
    
    >>> print(g(0).__iter__().next())
    g before 0
    g before 1
    g before 2
    g before 3
    3
    

