New submission from Ashish Shevale <[email protected]>:
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 <[email protected]>
<https://bugs.python.org/issue44216>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com