Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python + mypy + mixin = has no attribute error

I have Vscode + mypy error in the UI interface: "EngineMixin" has no attribute "engine" for the next Mixin class

class EngineMixin:
    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output

In fact, this error is shown only in Vscode UI interface. When I run mypy in cli, there are no errors. In general, I understand why this error appears, but is there any way to supress it in vscode?

Edited (added screen): screenshot

like image 275
ypeskov Avatar asked Sep 01 '26 03:09

ypeskov


1 Answers

For mixins that refer to the class they're being mixed into, you can use a type stub to let mypy know that self.engine is expected to exist

class EngineMixin:

    # Like this
    engine: Engine

    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output
like image 180
Oliver Rice Avatar answered Sep 02 '26 17:09

Oliver Rice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!