0

In python - a final class is a class that other classes can't inherit from because of various reasons(for example - bool class should always have only 2 instances - true or false).

However - in my case, I want to inherit from re.Match (the regex Match class). the thing is that this class is written in c and apparently the Py_TPFLAGS_BASETYPE flag is not enabled in the c-python implementation of this class.

if i would try:

class Region(re.Match):  # Error: type 're.Match' is not an acceptable base type
   ...

I'm not sure why this flag isn't enabled in this case but it could be great if I could at least try and not be restricted by a flag.

there is a pythonic way to prohibit inheritance(see) but is there a python way to allow inheritence?

I can try to solve it by enabling this flag in the c implementation but I want to avoid it.

I can also try rerefer each needed method and attribute by hand to inner match:re.Match variable(want to avoid this also).

I'm looking for a more 'Pythonic' solution. any ideas?

Eliav Louski
  • 3,593
  • 2
  • 28
  • 52
  • Even if you could inherit from `re.Match`, you couldn't `__init__` one by hand anyway: `re.Match()` says "cannot create 're.Match' instances". So how would you imagine getting your hands on an instance of a `Region` like this? โ€“ AKX Mar 17 '21 at 14:10

1 Answers1

1

I'd probably just use a simple proxy object รก la

class Region:
    def __init__(self, match: re.Match):
        self.__dict__["match"] = match  # hoop jumped due to __setattr__

    def __getattr__(self, key):
        return getattr(self.match, key)

    def __setattr__(self, key, value):
        raise NotImplementedError("Regions are read-only")
AKX
  • 152,115
  • 15
  • 115
  • 172