Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mypy

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?

like image 890
kurtgn Avatar asked Nov 02 '18 14:11

kurtgn


1 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.

like image 177
pawelswiecki Avatar answered Oct 08 '22 01:10

pawelswiecki