[New-bugs-announce] [issue42883] __init__ function may incur an incorrect behavior if passing a list as a parameter and set its default value as empty

Haoyang report at bugs.python.org
Sun Jan 10 09:43:44 EST 2021


New submission from Haoyang <mahaoyang7777 at 163.com>:

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()
    a.a.append(1)

    print(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 =  []
[1]
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!

----------
files: test.py
messages: 384765
nosy: haoyang9804
priority: normal
severity: normal
status: open
title: __init__  function may incur an incorrect behavior if passing a list as a parameter and set its default value as empty
type: behavior
versions: Python 3.9
Added file: https://bugs.python.org/file49732/test.py

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42883>
_______________________________________


More information about the New-bugs-announce mailing list