On Tue, Dec 22, 2020 at 08:28:30AM +1100, Steven D'Aprano wrote:
An alternative, which may be better or worse but is probably worth considering, is to create your own wrapper proxy for True and False, then use that.
It has come to my attention that my post may have been unclear. I don't mean to suggest that the *consumers* of the library be responsible for changing all uses of True/False bools into the special proxies.
Rather, I meant that the *library itself* should internally replace True/False with its own custom objects that hash and compare differently. Here's an untested sketch of a solution:
``` class Boolean(object): # Proxy the genuine True and False bools. def __init__(self, obj): self._obj = obj def __bool__(self): return self._obj def __eq__(self, other): return self is other def __hash__(self): return 17 + self._obj
TRUE = Boolean(True) FALSE = Boolean(False)
class MyDict(dict): def __getitem__(self, key): if key is True: key = TRUE elif key is False: key = FALSE return super().__getitem__(key) ```
and similar for `__setitem__` etc.
The caller of the library doesn't need to know that their data containing True/False bools are silently replaced by TRUE/FALSE inside the mapping. They just use True and False in their code as normal and it should all just work.
Subclassing dict is sometimes tricky to get right, you might find it easier to subclass collections.UserDict.