[issue44216] Bug in class method with optional parameter

Ashish Shevale report at bugs.python.org
Sun May 23 10:39:05 EDT 2021


New submission from Ashish Shevale <shevaleashish at gmail.com>:

Consider the following piece of code

class MyClass:
    def do_something(self, a, b = []):
        b.append(a)
        print("b contains", b)
    def caller(self):
        a = (1,2)
        self.do_something(a)

a = MyClass().caller()
a = MyClass().caller()
a = MyClass().caller()

For this, the expected output would be

b contains [(1, 2)]
b contains [(1, 2)]
b contains [(1, 2)]

But actually comes out to be 

b contains [(1, 2)]
b contains [(1, 2), (1, 2)]
b contains [(1, 2), (1, 2), (1, 2)]

This only happens if in the do_something method, we append 'a' directly to 'b'. Instead, if we create a copy of parameter 'b', and append 'a' to the copy, there are no such side effects

----------
messages: 394199
nosy: shevaleashish
priority: normal
severity: normal
status: open
title: Bug in class method with optional parameter
type: behavior
versions: Python 3.8

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


More information about the Python-bugs-list mailing list