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.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QBIFWIVXURAV4DO7SA3UDT2I4EWBFJ45/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to