Locking a custom dictionary

dictionary, locking, python

Solution

Override the `__setitem__` method with your desired behavior, call `dict.__setitem__(self, key, value`) to modify the base dictionary without going through your base logic.

class ImmutableDict(dict):
    def __setitem__(self, key, value):
        if key not in self:
             raise KeyError("Immutable dict")
        dict.__setitem__(self, key, value)

d = ImmutableDict(foo=1, bar=2)
d['foo'] = 3
print(d)
d['baz'] = 4 # Raises error

You'll also need to override `dict.update()` and `setdefault()` to avoid addition of keys. And possibly `dict.__delitem__()`, `dict.clear()`, `dict.pop()` and `dict.popitem()` to avoid removal of keys.

Problem

Good day pythonians, I want to make a custom dictionary with two main features: - All keys are declared on creation - It is impossible to add new keys or modify current ones (values are still modifiable) Right now code is this: ``` class pick(dict): """This will make delicious toffee when finished""" def __init__(self, *args): dict.__init__(self) for arg in args: self[arg] = None ``` Any help is much appreciated. upd: While solution is what I was looking for there is one problem: dictionary calls the `__setitem__` to add the items on the initialization and not finding the keys it raises the error. ``` cupboard = pick('milk') #raises error ``` upd1: all solved, thank you very much.

Original source