In python 3, if you define a defaultdict
, trigger the default values to be returned with a non-existent key, then that key will be automatically put into the dictionary?? This:
foo = defaultdict(int)
1 in foo # False
foo[1] # 0
1 in foo # True????
This seems erroneous to me. I feel like the purpose of defaultdict
is to allow the user to get a default value without putting that key in the dictionary. Why did the language developers choose this and how can I avoid it?
It's not about language design. You can choose not to use collection.defaultdict
.
You can define your own dictionary that act as you want by defining __missing__
method:
>>> class MyDefaultDict(dict):
... def __init__(self, default_factory):
... self.default_factory = default_factory
... def __missing__(self, key):
... # called by dict.__getitem__ when key is not in the dictionary.
... return self.default_factory()
...
>>>
>>> foo = MyDefaultDict(int)
>>> 1 in foo
False
>>> foo[1]
0
>>> 1 in foo
False
SIDE NOTE: defaultdict
is implemented using __missing__
.