Wrong number of iterations means whole function may have been wrongly called multiple times

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-04-25

A loop I had in my midi-file conversion code seemed to be iterating four times But I only expected it to print twice, since the iterable object I passed in only had two entries.

Here was the relevant code:

def calibrate_existing_dynamic_range_for(
    midi_data: mido.MidiFile, control_code: Optional[int] = None
) -> Tuple:
    for track in midi_data.tracks:
        print("Got a track")

What was going wrong? The issue was that this entire function containing the loop (calibrate_existing_dynamic_range_for) has unexpectedly been called twice! I.e. The same two items of data showed up twice, on different rounds.