I ran into this problem when working with defaultdict. Here’s a program that demonstrates it:
from collections import defaultdict
d1 = defaultdict(default_factory=dict)
d2 = defaultdict(dict)
print("d1's default_factory:", d1.default_factory)
print("d2's default_factory:", d2.default_factory)
try:
d1['key'].update({'a': 'b'})
except KeyError:
print("d1 caused an exception")
try:
d2['key'].update({'a': 'b'})
except KeyError:
print("d2 caused an exception")
The above outputs:
d1's default_factory: None
d2's default_factory: <class 'dict'>
d1 caused an exception
Should this happen?