3 ms·
>Python, as befits Python, has default behavior for instances that I believe is "is" equivalency Python dicts consider two keys the same if they have the same
by vharuck 5y ago
>Python, as befits Python, has default behavior for instances that I believe is "is" equivalency
Python dicts consider two keys the same if they have the same hash value and are "=="-equal. So __eq__ and __hash__ are the dunder methods to finagle. Python's sets are the same way.
A useful example is with the pathlib library.
from pathlib import Path
p = Path('a.txt')
q = Path('a.txt').absolute()
p is q # False
{p, q} # Only one element
"q" carries some different info than "p", but it refers to the same file location. So not considering them distinct values is a good decision for this package.
- joshuamorton 5y agoNote that this is an oversimplification, as p = Path('a.txt') q = Path('a.txt') p is q # False since p and q are different objects and "is" equality checks if the objects are the same (this can be interpreted approximately as "have the same memory address"), so it'll almost never be true. And in the cases where it is ( 2 is 2), you shouldn't rely on it, as most of them are optimizations.
- nirs 5y agop and q are the same file now, but after you change current directory their are not. They should never be equal.