Fix "maximum recursion depth exceeded while calling a Python object" by using while instead of recursion