'Is there a way to exit/end old recursions (function()) without finishing them?

I created a very short program that forces the RecursionError: maximum recursion depth exceeded while pickling an object to occur:

import sys
sys.setrecursionlimit(1)

AB,CD=0,0

def A():
    global AB
    AB+=1
    print('A',AB,CD)
    # End all () except for A
    B()
    print('A2')

def B():
    global AB
    AB+=1
    print('B')
    C()
    print('B2')

def C():
    global CD
    CD+=1
    print('C')
    D()
    A()
    print('D2')

def D():
    global CD
    CD+=1
    print('D')

A()

What you will get in shell is:

A 1 0
B
C
#<...> (a couple of lines that I cut out to make the post clearer)
C
D
A 9 8
Traceback (most recent call last):
  File "D:\!Z pulpitu\Python\VTX RE.py", line 34, in <module>
    A()
  File "D:\!Z pulpitu\Python\VTX RE.py", line 11, in A
    B()
  File "D:\!Z pulpitu\Python\VTX RE.py", line 18, in B
    C()
#<...> (a couple of lines that I cut out to make the post clearer, screenshot below)
  File "D:\!Z pulpitu\Python\VTX RE.py", line 11, in A
    B()
  File "D:\!Z pulpitu\Python\VTX RE.py", line 17, in B
    print('B')
RecursionError: maximum recursion depth exceeded while pickling an object

The question is: Can I somehow end/exit/quit/close/forget all the iterations of B(), C() and D() when I am in A() (more specifically where "# End all () except for A" is located) without resetting the values AB and CD? And will it solve the RecursionError?

Cause as far as I am aware, while D() ends itself cause it doesn't call any other recursion, B() and C() are still running in the background waiting for their called functions to finish so they can get to print('B2') and print('C2') respectively, taking unnecessary memory (which, with higher recursionlimit and more complicated objects can cause a MemoryError)



Solution 1:[1]

Okay I think I found a way to make it work thanks to the comments by user2357112 supports Monica and a bit of tinkering.

import sys
sys.setrecursionlimit(1)

AB,CD=0,0
RunFunction=1
Run=1

def A():
    global AB,RunFunction
    AB+=1
    print('A',AB,CD)
    RunFunction=2;Block=1 #Old B()
    if Block!=1:
        print('A2')

def B():
    global AB,RunFunction
    AB+=1
    print('B')
    RunFunction=3;Block=1 #Old C()
    if Block!=1:
        print('B2')

def C():
    global CD,RunFunction
    CD+=1
    print('C')
    D()
    RunFunction=1;Block=1 #Old A()
    if Block!=1:
        print('D2')

def D():
    global CD
    CD+=1
    print('D')
    return CD

while Run==1:
    if RunFunction==1:
        A()
    if RunFunction==2:
        B()
    if RunFunction==3:
        C()
    if RunFunction==0:
        Run=0

Currently it's still running with AB and CD being over 45000(compared to previous 9 and 8)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Silver Lynx