Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are there caveats of using mutable types as default parameters in functions in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading