I'm getting type checker errors on the following code, I would love to understand how to resolve the error.
The following base class has an abstract class method, I want that every child class that inherits from it will implement a decode function that returns an instance of the child class.
from abc import ABC, abstractmethod
from typing import TypeVar
TMetricBase = TypeVar("TMetricBase", bound="MetricBase")
class MetricBase(ABC):
@abstractmethod
def add(self, element: str) -> None:
pass # pragma: no cover
@classmethod
@abstractmethod
def decode(cls, json_str: str) -> TMetricBase:
pass # pragma: no cover
Child class looks like the following
import json
from typing import Any, Callable, List, Mapping, Optional
from something import MetricBase, TMetricBase
class DiscreteHistogramMetric(MetricBase):
def __init__(self, histogram: Optional[Mapping[str, int]]) -> None:
super().__init__()
self._histogram = dict(histogram) if histogram else {}
def add(self, element: str) -> None:
self._histogram[element] = self._histogram.get(element, 0) + 1
@classmethod
def decode(cls, json_str: str) -> "DiscreteHistogramMetric":
json_obj = json.loads(json_str)
histogram_map = json_obj["DiscreteHistogramMetric"]
return cls(histogram=histogram_map)
I'm getting the following error:
error: Return type of "decode" incompatible with supertype "MetricBase"
When changing decode's return type to TMetricBase, I get the following error:
error: Incompatible return value type (got "DiscreteHistogramMetric", expected "TMetricBase")