Deleting Keys from a Python 3.15 frozendict

The built-in frozendict supports union but not removal. Here is how to drop keys today, which approach costs you immutability, and when the O(n) copy matters.

Binary Buddies · 5 min read · 0 views

Python 3.15 adds a built-in frozendict (PEP 814), and it covers the additive side of immutability. The union operator returns a new instance: bar = foo | {'y': 2} gives you a new frozendict with both keys and leaves foo alone. What a Stack Overflow question points out is that nothing equivalent exists for removal.

Other ecosystems ship this. The asker cites C#'s ImmutableDictionary.Remove and Scala's - on Map. On the built-in type there is no delete method and no subtraction operator, and del d[k] cannot work on an immutable mapping.

The answers on that thread give three routes: rebuild the mapping with a filter, wrap the filter in a subclass method, or use the PyPI package of the same name. Each has a cost, and one of them quietly gives up the immutability you wanted in the first place.

Rebuild with a filter

The accepted answer (written against a 3.15 release candidate) does the plain thing: construct a new frozendict from the items you want to keep.

d = frozendict(k1=1, k2=2, k3=3)
without_k1 = frozendict((k, v) for k, v in d.items() if k != 'k1')
# frozendict({'k2': 2, 'k3': 3})

Removing several keys is the same shape with a membership test against a set:

drop = {'k1', 'k3'}
rest = frozendict((k, v) for k, v in d.items() if k not in drop)

Note the semantics differ from del. A key that is not present is silently ignored, where del d['missing'] would raise KeyError. If you want the strict behaviour, you have to check yourself.

The clever version is not worth it

A second answer tried to avoid the explicit loop using set-like operations on the keys view, and concluded the result is worse than the obvious filter:

from operator import itemgetter
to_exclude = {2}
frozendict(zip(keys := a.keys() - to_exclude, itemgetter(*keys)(a)))

It is still O(n). The loop has moved inside zip, and you pay for that in readability. It also has edge cases the author does not mention. itemgetter called with a single key returns the bare value rather than a tuple, and called with no keys it raises TypeError. Subtracting from a keys view also produces a plain set, so the original key order is not what you iterate. Treat it as a demonstration that the generator expression is the right tool.

Put it in a subclass method

If you remove keys in more than one place, the same answer suggests subclassing and giving the filter a name:

class DFrozenDict(frozendict):
    def delitem(self, key):
        if key not in self:
            raise KeyError(key)
        return type(self)(item for item in self.items() if item[0] != key)

a = DFrozenDict({1: 11, 2: 22, 3: 33})
a.delitem(2)   # DFrozenDict({1: 11, 3: 33})

The method is deliberately not called __delitem__. The del statement discards any return value, so a copy produced by removing one item would go nowhere. The original object cannot change, so the operation has to be a method that returns the new mapping.

This version restores the KeyError behaviour, and type(self) keeps the subclass through the copy. One naming warning: the answer's usage example assigns the result to popped, but the return value is the remaining mapping, not the removed value. Pick a name that does not suggest dict.pop.

The PyPI package has delete()

The frozendict project on PyPI (pip install frozendict) has an API similar to the 3.15 built-in, plus extra methods: set(key, value), delete(key), setdefault(key[, default]), key([index]), value([index]) and item([index]). Removal becomes one call:

from frozendict import frozendict
d = frozendict(k1=1, k2=2, k3=3)
d.delete('k1')
# frozendict.frozendict({'k2': 2, 'k3': 3})

The catch, from the accepted answer: the package type is a dict subclass, so a frozendict instance can still be modified through ordinary dict methods. For a codebase adopting frozendict specifically for immutability, that undermines the point. The type also has the same name as the built-in, so check which one a given module is importing.

Where this does not fit

Every route here copies the whole mapping. The filter is O(n), and the subclass method does the same work. Removing one key from a large frozendict in a hot loop, or removing keys one at a time in sequence, repeats that copy each time. In that case batch the removals into a single filter pass, or build the mapping in a regular dict and freeze it once at the end.

The PyPI package is a poor fit if you need real immutability guarantees, given the dict-subclass behaviour above. The subclass approach is also a convention rather than a standard. Anyone reading the code has to know delitem is yours, not part of the type. If you only delete in one or two places, the inline generator expression is probably the least surprising choice.

This article draws on Delete operation on frozendict and answers to it (1, 2), on the Stack Exchange network, licensed under CC BY-SA 4.0.

  • #PEP 814
  • #Python
  • #frozendict
  • #immutability
  • #python-3.15

Comments

Add a comment
Sign in with Google to join the conversation