Why default arguments value is mutable if param initiated by call?

Question:

I am using PyCharm (Python 3) to write a Python function which accepts an empty dictionary or list as an argument.

def my_function(param1: list = list(), param2: dict = dict()):
    ...

But PyCharm yellowed this.
How dict() or list() can be mutable? Is this PyCharm bug?

Asked By: Daniel Kanzel

||

Answers:

No, it’s not a PyCharm bug, it’s PyCharm trying to prevent you from writing bugs.

The list() and dict() functions are called at the time you declare that function, and the single (reusable, mutable) list or dict returned by that call becomes the parameter default.

From there on it’s just "Least Astonishment" and the Mutable Default Argument all again.

To wit:

>>> def my_function(param1: list = list(), param2: dict = dict()):
...     param1.append("hi")
...     param2[len(param2)] = "hello"
...
>>> my_function.__defaults__
([], {})
>>> my_function()
>>> my_function.__defaults__
(['hi'], {0: 'hello'})
>>> my_function()
>>> my_function.__defaults__
(['hi', 'hi'], {0: 'hello', 1: 'hello'})
>>> my_function()
>>> my_function.__defaults__
(['hi', 'hi', 'hi'], {0: 'hello', 1: 'hello', 2: 'hello'})
Answered By: AKX

Check the link to the existing answer

Answered By: Nicholas W.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.