From 8e3e4af3d0b3462d1a143f9544ce8777209b5908 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Sat, 27 Mar 2021 13:47:10 -0400 Subject: [PATCH] Add freezable dict --- importlib_metadata/_collections.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 importlib_metadata/_collections.py diff --git a/importlib_metadata/_collections.py b/importlib_metadata/_collections.py new file mode 100644 index 00000000..f0357989 --- /dev/null +++ b/importlib_metadata/_collections.py @@ -0,0 +1,21 @@ +import collections + + +class freezable_defaultdict(collections.defaultdict): + """ + Mix-in to freeze a defaultdict. + + >>> dd = freezable_defaultdict(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()