The below function retains the values in its list every time it is run. I recently learned about this issue as a Python 'gotcha' due to using a mutable default argument.
How do I fix it? Creating a global variable outside the function causes the same issue. Passing a list into the function breaks the recursion and only displays the first level of categories.
def build_category_list(categories, depth=0, items=[]):
'''Builds category data for parent select field'''
for category in categories:
items.append((category.id, '-' * depth + ' ' + category.name))
if category.children:
build_category_list(category.children, depth + 1)
return items