Re: A proposal to modify `None` so that it hashes to a constant
Steven D'Aprano <[email protected]> Sun, 4 Dec 2022 14:20:18 +1100
| Newsgroups | gmane.comp.python.devel |
|---|---|
| Message-ID | <[email protected]> |
On Thu, Dec 01, 2022 at 10:18:49PM +0000, Rob Cliffe via Python-Dev wrote:
> Wild suggestion:
> Make None.__hash__ writable.
> E.g.
> None.__hash__ = lambda : 0 # Currently raises AttributeError:
> 'NoneType' object attribute '__hash__' is read-only
You would have to write to `type(None).__hash__` because of the way
dunders work.
Now imagine that you have twenty different libraries or functions or
classes, each the `__hash__` method to a different function. Chaos.
You can simulate that chaos with this:
```
import random
class ChangingHash:
def __repr__(self):
return "MyNone"
def __hash__(self):
# Simulate the effect of many different callers changing
# the hash value returned at unpredictable times.
return random.randint(1, 9)
MyNone = ChangingHash()
data = {MyNone: 100}
print(MyNone in data) # 8 in 9 chance of printing False
data[MyNone] = 200
print(data) # 8 in 9 chance of {MyNone: 100, MyNone: 200}
print(MyNone in data) # now 7 in 9 chance of printing False
```
--
Steve