As you may know, implementing a __getitem__
method makes a class iterable:
class IterableDemo:
def __getitem__(self, index):
if index > 3:
raise IndexError
return index
demo = IterableDemo()
print(demo[2]) # 2
print(list(demo)) # [0, 1, 2, 3]
print(hasattr(demo, '__iter__')) # False
However, this doesn't hold true for regex match objects:
>>> import re
>>> match = re.match('(ab)c', 'abc')
>>> match[0]
'abc'
>>> match[1]
'ab'
>>> list(match)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_sre.SRE_Match' object is not iterable
It's worth noting that this exception isn't thrown in the __iter__
method, because that method isn't even implemented:
>>> hasattr(match, '__iter__')
False
So, how is it possible to implement __getitem__
without making the class iterable?