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

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

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?

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 :

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'})
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