Callback functions in python

def chunks_process(chunks, pos, folder_name, whole_text):
    r = sr.Recognizer()
    for i in range(pos, len(chunks)):
        chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
        chunks[i].export(chunk_filename, format="wav")
        with sr.AudioFile(chunk_filename) as source:
            audio_listened = r.record(source)
                text = r.recognize_google(audio_listened, language='vi-VN')
                chunks_process(chunks, i, folder_name, whole_text)
                text = f"{text.capitalize()}. "
                print(chunk_filename, ":", text)
                whole_text += text
    return whole_text

I want to callback chunks_process() funtion whenever r.recognize_google() api call fail at the specific position.

I have a problem that it repeat the for loop after finishing the end index of an array(chunks).

I don’t know how to resolve this problem.


This happens because you do not stop when getting back from a recursive call. The i of the caller is not updated by the i of the recursive execution.

The solution is to return immediately when you get back from recursion, because at that point all is processed. So add return here:

     return chunks_process(chunks, i, folder_name, whole_text)

As a side note: it seems that with the recursive call you want to retry an operation. I would not use recursion for that, but just write an additional loop that keeps iterating as long as a retry is needed.