Your settings proxy now logs every read and turns away a bad write. The desk record also carries archived: 1, a retired setting that old dashboards still read. New dashboard code asks key in settings before it shows a setting, and that check should return false for archived without breaking old readers. The team also wants level to survive any stray delete.
Neither operation reaches the get or set traps you’ve written. In this lesson, you’ll give in and delete their own rules and learn where those rules stop.
Answer in With a has Trap
In Python, a mapping-style settings class decides what in means by defining __contains__(), and __delitem__() decides what del settings["level"] does:
class Settings:
def __init__(self, values):
self._values = values
def __contains__(self, name):
return name in self._values and name != "archived"
def __delitem__(self, name):
if name == "level":
raise KeyError("level can't be deleted")
del self._values[name]
settings = Settings({"level": 2, "label": "desk", "archived": 1})
print("archived" in settings, "level" in settings)
del settings["level"]
The retired key stays in _values, but in no longer admits it, and deleting level raises the error you chose. This shortened output omits the traceback’s file and source lines:
False True
Traceback (most recent call last):
...
KeyError: "level can't be deleted"
As before, new Proxy(target, handler) wraps a target, and each handler method intercepts one operation, as each Python dunder hooks into one operator. The has trap runs whenever in asks about a property of the proxy. It receives the target and the key and returns true or false: