Why does PyCharm warn about mutable default arguments? How can I work around them?

If you don’t alter the “mutable default argument” or pass it anywhere where it could be altered just ignore the message, because there is nothing to be “fixed”.

In your case you only unpack (which does an implicit copy) the “mutable default argument” – so you’re safe.

If you want to “remove that warning message” you could use None as default and set it to {} when it’s None:

def put_wall_post(self,message,attachment=None,profile_id="me"):
    if attachment is None:
        attachment = {}

    return self.put_object(profile_id,"feed",message = message,**attachment)

Just to explain the “what it means”: Some types in Python are immutable (int, str, …) others are mutable (like dict, set, list, …). If you want to change immutable objects another object is created – but if you change mutable objects the object remains the same but it’s contents are changed.

The tricky part is that class variables and default arguments are created when the function is loaded (and only once), that means that any changes to a “mutable default argument” or “mutable class variable” are permanent:

def func(key, value, a={}):
    a[key] = value
    return a

>>> print(func('a', 10))  # that's expected
{'a': 10}
>>> print(func('b', 20))  # that could be unexpected
{'b': 20, 'a': 10}

PyCharm probably shows this Warning because it’s easy to get it wrong by accident (see for example Why do mutable default arguments remember mutations between function calls? and all linked questions). However, if you did it on purpose (Good uses for mutable function argument default values?) the Warning could be annoying.

Leave a Comment