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
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?