I'm fully aware that pylint
and other static analysis tools are not all-knowing, and sometimes their advice must be disobeyed. (This applies for various classes of messages, not just convention
s.)
If I have classes like
class related_methods():
def a_method(self):
self.stack.function(self.my_var)
class more_methods():
def b_method(self):
self.otherfunc()
class implement_methods(related_methods, more_methods):
def __init__(self):
self.stack = some()
self.my_var = other()
def otherfunc(self):
self.a_method()
Obviously, that's contrived. Here's a better example, if you like.
I believe this style is called using "mixins".
Like other tools, pylint
rates this code at -21.67 / 10
, primarily because it thinks more_methods
and related_methods
don't have self
or attributes otherfunc
, stack
, annd my_var
because without running the code, it apparently can't see related_methods
and more_methods
are mixed-in to implement_methods
.
Compilers and static analysis tools can't always solve the Halting Problem, but I feel this is certainly a case in which looking at what's inherited by implement_methods
would show this is perfectly valid, and that would be a very easy thing to do.
Why do static analysis tools reject this valid (I think) OOP pattern?
Either:
-
They don't even try to check inheritance or
-
mixins are discouraged in idiomatic, readable Python
#1 is obviously incorrect because if I ask pylint
to tell me about a class of mine that inherits unittest.TestCase
that uses self.assertEqual
, (something defined only in unittest.TestCase
), it does not complain.
Are mixins unpythonic or discouraged?
Best Answer
Mixins just aren't a use case that was considered by the tool. That doesn't mean it's necessarily a bad use case, just an uncommon one for python.
Whether mixins are used appropriately in a particular instance is another matter. The mixin anti-pattern I see most frequently is using mixins when there is only ever intended to be one combination mixed. That's just a roundabout way to hide a god class. If you can't think of a reason right now to swap out or leave out one of the mixins, it shouldn't be a mixin.