Add a dict method to convert to a frozendict?

I created a draft pull request adding dict.take_frozendict(), list.take_tuple() and set.take_frozenset() methods (first commit), and modifying the stdlib to use these new methods (second commit), to see how it can look alike: PR: Add dict.take_frozendict() method.

Note: Don’t use this PR to run benchmarks, the implementation is naive (not O(1)). For my benchmarks, I used a different efficient implementation (O(1)).

Some examples using this new methods.

Function converting a temporary list to a tuple:

    @property
    def args(self):
        args = []
        for param_name, param in self._signature.parameters.items():
            ...
            if param.kind == _VAR_POSITIONAL:
                # *args
                args.extend(arg)
            else:
                # plain argument
                args.append(arg)

-        return tuple(args)
+        return args.take_tuple()

Function converting a temporary dict to a frozendict:

def _deepcopy_frozendict(x, memo, deepcopy=deepcopy):
    y = {}
    for key, value in x.items():
        y[deepcopy(key, memo)] = deepcopy(value, memo)
    ...
-    return frozendict(y)
+    return y.take_frozendict()

Convert a list-comprehension to a tuple:

-        return tuple([_asdict_inner(v, dict_factory) for v in obj])
+        return [_asdict_inner(v, dict_factory) for v in obj].take_tuple()

Convert a set-comprehension to a frozenset:

-_ATTRIB_DENY_LIST = frozenset({
+_ATTRIB_DENY_LIST = {
     name.removeprefix("assert_")
     for name in dir(NonCallableMock)
     if name.startswith("assert_")
-})
+}.take_frozenset()

Frozendict literal, when frozendict(key=value, ...) syntax cannot be used:

-_capability_names = frozendict({
+_capability_names = {
     _curses.KEY_A1: 'ka1',
     _curses.KEY_A3: 'ka3',
     _curses.KEY_B2: 'kb2',
     ...
-    })
+    }.take_frozendict()

Frozenset literal:

-    _ID_KEYWORDS = frozenset({"True", "False", "None"})
+    _ID_KEYWORDS = {"True", "False", "None"}.take_frozenset()
3 Likes