In python, an object is subscriptable when it's class defines a
__getitem__(self, k)
method, allowing us to "get items" through the bracket syntax:
obj[k]
The syntax for the builtin del function is:
del(obj[k])
This deletes item k from (subscriptable) object obj. But apparently, without calling the special getitem method.
See example below
>>> class A:
... def __init__(self, d):
... self._d = d
...
... def __getitem__(self, k):
... print("Calling __getitem__")
... return self._d[k]
...
... def __delitem__(self, k):
... del(self._d[k])
...
>>>
>>> a = A({1: 'one', 2: 'two', 3: 'three'})
>>> a._d
{1: 'one', 2: 'two', 3: 'three'}
>>> a[2]
Calling __getitem__
'two'
>>> del(a[2])
>>> # Note there was no "Calling __getitem__" print!
So it seems like before a[2] forwards the work to the getitem method, the interpreter is aware of the del context, and bypasses it, calling directly
a.__delitem__(2)
instead.
How does that work?
And most of all: Is this mechanism customizable?
Could I for example, write a function foo so that
foo(obj[k])
doesn't ever call
obj.__getitem__(k)
but instead, for example,
obj.foo(k)