[Python-Dev] Re: A proposal to modify `None` so that it hashes to a constant

2022年12月04日 16:28:02 -0800

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
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/ZEQFHMIQJIO5AWYTLSW7PKPZE2RZMJMY/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to