This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: __init__ function may incur an incorrect behavior if passing a list as a parameter and set its default value as empty
Type: behavior Stage: resolved
Components: Versions: Python 3.9
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: haoyang9804, serhiy.storchaka
Priority: normal Keywords:

Created on 2021-01-10 14:43 by haoyang9804, last changed 2022-04-11 14:59 by admin. This issue is now closed.

File name Uploaded Description Edit haoyang9804, 2021-01-10 14:43 This code snippet trigger this incorrect behavior.
Messages (3)
msg384765 - (view) Author: Haoyang (haoyang9804) Date: 2021-01-10 14:43
Here is the bug-triggered code snippet in the file uploaded

class A:
    def __init__(self, b=[]):
        print('b = ', b)
        self.a = b 

for i in range(3):
    a = A()


It seems that when I pass a list "b" to __init__ function with default value empty list. Every time I create a new instance of this class and append one new variable to "self.a", the default value of "b" changed at the next time I create another instance of class A.

The outcome of this code snippet is 
a =  []
a =  [1]
[1, 1]
a =  [1, 1]
[1, 1, 1]

I am new to python. Is it a legal behavior in python? If yes, what is the principle beneath it? Thanks in advance!
msg384766 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-01-10 14:58
msg384767 - (view) Author: Haoyang (haoyang9804) Date: 2021-01-10 15:00
Date User Action Args
2022-04-11 14:59:40adminsetgithub: 87049
2021-01-10 15:00:28haoyang9804setmessages: + msg384767
2021-01-10 14:58:42serhiy.storchakasetstatus: open -> closed

nosy: + serhiy.storchaka
messages: + msg384766

resolution: not a bug
stage: resolved
2021-01-10 14:43:44haoyang9804create