Exposing `defaultdict` as a regular `dict`

defaultdict docs say for default_factory:

If the default_factory attribute is None, this raises a KeyError
exception with the key as argument.

What if you just set your defaultdict’s default_factory to None? E.g.,

>>> d = defaultdict(int)
>>> d['a'] += 1
>>> d
defaultdict(<type 'int'>, {'a': 1})
>>> d.default_factory = None
>>> d['b'] += 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'b'
>>> 

Not sure if this is the best approach, but seems to work.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)