How to fulfill ABC class definition of abstract properties in child class in Python

55 views Asked by At

I have the following abc class:

class Logger(ABC):
    @abstractproperty
    def filename_prefix(self):
        pass

    @abstractproperty
    def trace_id_length(self):
        pass

    @abstractproperty
    def run_id_length(self):
        pass

    def __init__(self):
        self._load_history()

    def _load_history(self):
        try:
            with open(
                os.path.join(trace_history_dir, f"{self.filename_prefix}_history.json"),
                "r",
            ) as f:
                history = json.load(f)
        except Exception as e:
            if e.__class__.__name__ == "FileNotFoundError":
                history = {"0".zfill(self.trace_id_length): "Init"}

                with open(
                    os.path.join(
                        trace_history_dir, f"{self.filename_prefix}_history.json"
                    ),
                    "w",
                ) as f:
                    json.dumps(history)
            else:
                raise e

        return history

And the following child class:

class CostsLogger(Logger):
    def __init__(self):
        self.filename_prefix = filename_prefix
        self.trace_id_length = 4
        self.run_id_length = 4

        super.__init__()

The problem is that I'm getting this error when running:

Can't instantiate abstract class CostsLogger with abstract methods filename_prefix, run_id_length, trace_id_length

I don't want to force programmers to use @property when implementing a child class but keep the @abstractporperty's in the abstract class definition to enforce their implementation, is there any way to avoid it?

0

There are 0 answers