Search code examples
pythonmagic-methods

Python __index__ special method


>>> class Thing(object):
...     def __index__(self):
...         return 1
... 
>>> thing = Thing()
>>> list_ = ['abc', 'def', 'ghi']
>>> list_[thing]
'def'
>>> dict_ = {1: 'potato'}
>>> dict_[thing]
# KeyError

How does thing know to represent itself as 1 when accessed by a list, but not by a dict? Don't both magic methods go through __getitem__? The usage shown for lists could go through __int__ instead so what is the raison d'être for __index__ anyway?


Solution

  • Dict and List does not implement __getitem__ the same way. Dict objects uses a comparison (__eq__) on __hash__ of objects as key to use in __getitem__.

    To make Thing usable for dict you have to implement both hash and eq.