79360407

Date: 2025-01-16 05:01:10
Score: 1.5
Natty:
Report link

I have noticed something disturbing, on both setdefault and get on a dict:

class A:
    def __init__(self):
        print('A-constructor called')
        self.names = []
    def add_name(self, name):
        self.names.append(name)

a = A()
A-constructor called
a.add_name('a1')
a
<__main__.A object at 0x7f9cdaabe570>
a.names
['a1']
d = {'A':a}
a1 = d.setdefault('A', A())
A-constructor called
id(a)
140311660324208
id(a1)
140311660324208
a1.names
['a1']
a2 = d.get('A',A())
A-constructor called
id(a2)
140311660324208

a2 = d.get('A',A()) A-constructor called id(a2) 140311660324208

even though, when using setdefault or get on d(with 'A' entry), where as I expect, the constructor of A should not be called, but in both cases, the constructor is called! even though a, a1, and a2 are all having the same id. But, the calling of the constructor is not logic, and may cause mayhem! Is this a bug? or I understand it wrongly?

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: jianchi wei