Question

I'm working on a function in which i would like to know if an object is an instance of re.MatchObject. I tried to use isinstance but re.MatchObject is a C type and this does not work.

I still can do an alternative test like hasattr( ... , 'pos') or any other re.MatchObject attribute, but i don't consider it as a good solution. Any other way ?

Was it helpful?

Solution

You'd need to use the proper type; the match object type is not explicitly importable, but you can use type() on an existing instance to store it:

import re

MatchObject = type(re.search('', ''))

then use that in isinstance() tests:

>>> MatchObject = type(re.search('', ''))
>>> isinstance(re.search('', ''), MatchObject)
True

There is nothing about C-defined Python types that prevents using isinstance() otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top