mypy: how to ignore "missing attribute" errors in mixins

Question:

I cannot get mypy to work properly with mixins: it keeps complaining that my mixins reference missing attributes. Consider this example:

class PrintValueMixin:
    """A mixin that displays values"""

    def print_value(self) -> None:
        print(self.value)


class Obj(PrintValueMixin):
    """An object that stores values. It needs a mixin to display its values"""

    def __init__(self, value):
        self.value = value


instance = Obj(1)
instance.print_value()

If I run mypy on this file, I get an error:

error: "PrintValueMixin" has no attribute "value"

Of course it has no attribute “value”. It is a mixin, it should not have its own attributes!

So how do I make mypy understand this?

Asked By: kurtgn

||

Answers:

I think this is a sign of an imperfectly designed class hierarchy. Mixins should not depend on stuff that are in classes inheriting them. I know this is against duck typing, but we are in “static” typing realm and rules are more strict here.

If you want to get rid of the issue without refactoring the code you can do the following:

class PrintValueMixin:
    """A mixin that displays values"""
    value: int   # or whatever type it has

    def print_value(self) -> None:
        print(self.value)                                

Now, the error is gone. It’s because mypy sees value as a class attribute. Mind that it’s uninitialized – value doesn’t have any object bind to it. Thus, this has no real consequence in runtime and you won’t use it by mistake.

Answered By: pawelswiecki
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.