How to subclass MatchObject in Python?

I played with regular expressions and tried to subclass the MatchObject that comes back from re.search.

I was not lucky to access the MatchObject class.

I suggest entering the code here that the actual type of this object is not called "MatchObject":

>>> re.search ("a", "a")
<_sre.SRE_Match object at 0x100427a58>

However, I cannot access this object:

import _sre

dir (_sre)
['CODESIZE', 'MAGIC', '__doc__', '__name__', '__package__', 'compile', 'copyright', 'getcodesize', 'getlower']

>>> dir(_sre.SRE_Match)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'SRE_Match'

What am I missing?

+3
source share
1 answer

This will not happen :)

>>> import re
>>> mo = re.search ("a", "a")
>>> mo_class = type(mo)
>>> mo_class
<type '_sre.SRE_Match'>
>>> class SubClass(mo_class):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    type '_sre.SRE_Match' is not an acceptable base type

It is worth noting that you can always access the type of object by calling type(obj)though.

+2
source

Source: https://habr.com/ru/post/1788647/


All Articles