Skip to content

Commit

Permalink
Add FreezableDefaultDict
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Mar 28, 2021
1 parent 9da453c commit 99e0dcd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
v3.3.0
======

Add ``FreezableDefaultDict``.

v3.2.0
======

Expand Down
23 changes: 23 additions & 0 deletions jaraco/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -961,3 +961,26 @@ def pop_all(items):
"""
result, items[:] = items[:], []
return result


# mypy disabled for pytest-dev/pytest#8332
class FreezableDefaultDict(collections.defaultdict): # type: ignore
"""
Often it is desirable to prevent the mutation of
a default dict after its initial construction, such
as to prevent mutation during iteration.
>>> dd = FreezableDefaultDict(list)
>>> dd[0].append('1')
>>> dd.freeze()
>>> dd[1]
[]
>>> len(dd)
1
"""

def __missing__(self, key):
return getattr(self, '_frozen', super().__missing__)(key)

def freeze(self):
self._frozen = lambda key: self.default_factory()

0 comments on commit 99e0dcd

Please sign in to comment.