I have recently read about mutable default parameters in Python. For some reason, I came up with an idea of using it like this:
data = [3, 4, 1, 8, 5, 9, 2, 6, 7]
def get_min(checked=[]):
global data
mn = min((x for x in data if x not in checked))
checked.append(mn)
return mn
The code is pretty useless, and it can easily be replaced by a generator, but I am wondering if I should ever use such a technique in my projects. Are there any hidden caveats of doing such a thing?
I have read some similar questions, but all I see are constant arguments about how this thing is a design flaw. So I want to get a clear answer: should I use it, or shouldn't I, and why?
The main caveat is that someone reading your code later, unless they're familiar with this particular gotcha, might not understand that checked
persists, or that the caller isn't actually intended to ever provide a value for it. Assuming you wanted to avoid generators, it would be more clear to write something like:
data = [3, 4, 1, 8, 5, 9, 2, 6, 7]
checked = []
def get_min():
mn = min(x for x in data if x not in checked)
checked.append(mn)
return mn