Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the proper way to ignore “missing attribute” errors in mixins? #5868

Closed
kurtgn opened this issue Nov 3, 2018 · 6 comments · Fixed by #7860
Closed

What is the proper way to ignore “missing attribute” errors in mixins? #5868

kurtgn opened this issue Nov 3, 2018 · 6 comments · Fixed by #7860

Comments

@kurtgn
Copy link

kurtgn commented Nov 3, 2018

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 what is the proper way to deal with typechecking mixins?

@ethanhs
Copy link
Collaborator

ethanhs commented Nov 5, 2018

This was actually recently asked and answered here: #5837

I think we should probably add something in the docs (maybe common_issues.rst since this seems to be a frequent problem.

@JukkaL
Copy link
Collaborator

JukkaL commented Nov 5, 2018

Agreed, this is worth documenting. I'm increasing priority this is something I'd be happy to accept as a contribution.

@AndrewUshakov
Copy link

Why solution below (define mixin class as an abstract class) is unacceptable? Pycharm also will not generate warning. Without such modification attempt to directly instantiate mixin class will generate run time error and both mypy and Pycharm properly warn about this possibility.

from abc import ABC, abstractmethod


class PrintValueMixin(ABC):
    """A mixin that displays values"""

    @abstractmethod
    def __init__(self):
        self._value = None

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

    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):
        super().__init__()
        self.value = value


if __name__ == '__main__':

    instance = Obj(1)
    instance.print_value()

@kurtgn
Copy link
Author

kurtgn commented Nov 11, 2018

@AndrewUshakov

Looks like this would work - but imagine the amount of boilerplate this would involve if there are several mixins manipulating several values. A simple example - one mixin displaying the value and another one changing the value. Do they both need setters and getters for the value property?

@kurtgn
Copy link
Author

kurtgn commented Nov 11, 2018

There's another suggestion from stackoverflow which I like for its brevity - :just declaring property type on the mixin class:

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

    value: int

    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):
        super().__init__()
        self.value = value

    def change_value(self):
        self.value = 'changed'


if __name__ == '__main__':

    instance = Obj(1)
    instance.print_value()

@ziima
Copy link

ziima commented Oct 22, 2019

@kurtgn: declaring attribute is fine, when there is just few of them. I gets annoying a lot with the growing number of attributes. And the same problem applies to methods.

ilevkivskyi added a commit to ilevkivskyi/mypy that referenced this issue Nov 5, 2019
Fixes python#3625
Fixes python#5305
Fixes python#5320
Fixes python#5868
Fixes python#7191
Fixes python#7778
Fixes python/typing#680

So, lately I was noticing many issues that would be fixed by (partially) moving the check for self-type from definition site to call site.

This morning I found that we actually have such function `check_self_arg()` that is applied at call site, but it is almost not used. After more reading of the code I found that all the patterns for self-types that I wanted to support should either already work, or work with minimal modifications. Finally, I discovered that the root cause of many of the problems is the fact that `bind_self()` uses wrong direction for type inference! All these years it expected actual argument type to be _supertype_ of the formal one.

After fixing this bug, it turned out it was easy to support following patterns for explicit self-types:
* Structured match on generic self-types
* Restricted methods in generic classes (methods that one is allowed to call only for some values or type arguments)
* Methods overloaded on self-type
* (Important case of the above) overloaded `__init__` for generic classes
* Mixin classes (using protocols)
* Private class-level decorators (a bit hacky)
* Precise types for alternative constructors (mostly already worked)

This PR cuts few corners, but it is ready for review (I left some TODOs). Note I also add some docs, I am not sure this is really needed, but probably good to have.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants