Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match object not iterable – why?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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__?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading