Since Python 3.6, a match object is subscriptable.
According to one of the definitions of an iterable, it is sufficient to have __getitem__() implemented and to return values on indexes until it raises IndexError.
See here and also:
class A:
def __getitem__(self, index):
if index > 10: raise IndexError
return index * index
list(A()) # -> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
This seems to be fulfilled by the new match objects:
import re
r = re.compile("(.)(.)")
m = r.match("ab") # -> <_sre.SRE_Match object; span=(0, 2), match='ab'>
m[0] # -> 'ab'
m[1] # -> 'a'
m[2] # -> 'b'
And yet,
list(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_sre.SRE_Match' object is not iterable
If I wrap it in a class like this:
class B:
def __init__(self, a):
self.a = a
def __getitem__(self, i):
return self.a[i]
it works:
list(B(m)) # -> ['ab', 'a', 'b']
Why is that? What exactly prevents that from working?
>Solution :
I’m terribly sorry, for some reason my flag and comment functions are not working. This is answered in How come regex match objects aren't iterable even though they implement __getitem__?