lundi 27 septembre 2021

How can I avoid a warning in a child class due to attribute covariance?

I am trying to avoid the linter warning that is shown as a comment in the last line of the code sample.

I understand why it happens, and I know I could very well ignore because this is Python. But as a sort of self-exercise, I've been trying to think of a properly typed way to avoid it, and haven't been able to find a solution.

Here's a code sample:

class Content(ABC):
    def __init__(self, data: Dict):
        self._data: Dict = data


class AlertContent(Content):
    def __init__(self, alert: Alert):
        data: Dict = get_data_from_alert(alert)
        super().__init__(data)
        self.alert_priority: str = alert.priority


class Envelope(ABC):
    def __init__(self, content: Content):
        self._content: Content = content
    
    @property
    @abstractmethod
    def priority(self) -> str:
        raise NotImplementedError


class AlertEnvelope(Envelope):
    def __init__(self, content: AlertContent):
        super().__init__(content)

    @property
    @abstractmethod
    def priority(self) -> str:
        return self._content.alert_priority  # Warning: Unresolved attribute reference 'alert_priority' for class 'Content'

Do you have any ideas?

Aucun commentaire:

Enregistrer un commentaire