0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Oleksandr Novik
  • 489
  • 9
  • 24

1 Answers1

3

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
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • So there are no technical secrets behind this thing, that can possibly break it? Only the matter of knowledge? – Oleksandr Novik Jan 07 '22 at 20:33
  • 2
    There generally aren't "secrets" in programming. Things work the way they work. With a few specific exceptions, nobody intentionally designs a language with hidden random pitfalls. :) – Samwise Jan 07 '22 at 20:40
  • 1
    In other words @aleksandr-novik, in a sense, yes, but in a more important sense, "technical secret" and "matter of knowledge" are *the same thing*. They feel different when the piece of knowledge you were missing is unexpected, surprising, or from a lower level of abstraction, and caused some code to behave in a way you didn't expect. Technical secrets are the result of designing things while feeling that these kinds of "matter of knowledge" effects are okay. – mtraceur Jan 07 '22 at 21:11