0

Two scoops of Django, best practices for Django 1.8 by Daniel Roy Greenfeld and Audrey Roy Greenfeld.

Paragraph 10.2 Using Mixins with CBWs:

Mixins should inherit from Python’s built-in object type.

And example:

from django.views.generic import TemplateView
class FreshFruitMixin(object):
    def get_context_data(self, **kwargs):
        context = super(FreshFruitMixin, self).get_context_data(**kwargs)
        context["has_fresh_fruit"] = True
        return context

class FruityFlavorView(FreshFruitMixin, TemplateView):
    template_name = "fruity_flavor.html"

I just can't catch the idea. Why should we inherit from object? Can't we write something like this?

class ClassNameMixin:
    <statement-1>

This will be the same. So, I just can't understand why inheriting from object is that important here.

Then, the mixin performs something. Can't it inherit from some fruitful class?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Michael
  • 4,273
  • 3
  • 40
  • 69
  • I'm sure theres a duplicate around but it makes your code compatible with Python 2.7 – Sayse Jul 01 '16 at 07:16
  • 1
    Possible duplicate of [Python Default Inheritance?](http://stackoverflow.com/questions/4906014/python-default-inheritance) – Sayse Jul 01 '16 at 07:17
  • This is not a duplicate question. You may be right about compatibility. But what about imperative restriction on inheritance from a meaningful class? – Michael Jul 01 '16 at 07:34
  • I'm not sure what you mean, I interpreted your question as asking what is different with `Class(object)` and `Class`, which is detailed in the duplicate – Sayse Jul 01 '16 at 07:36
  • No, this is not a duplicate at all. Compare. My question: why should I always inherit from object. That question: if there is no implicit inheritance in a class, which class does it inherit from? For me it is quite different questions. – Michael Jul 01 '16 at 07:44
  • Read about [new- & old-style classes](https://wiki.python.org/moin/NewClassVsClassicClass) – ohrstrom Jul 01 '16 at 08:18

1 Answers1

3

This remark applies to Python2, where, when none base class is specified, an old-style class is created and MRO and super() won't work, which are crucial for multiple inheritance.

In Python3, there are no old-style classes and every class/type (indirectly) inherits from object.

I also believe that there is nothing wrong with inheriting mixins from other classes. This is just multiple inheritance and all the rules and traps apply. So, the remark in question could read:

Mixins should (indirectly) inherit from Python’s built-in object type.

Sometimes it's also recommended to explicitly inherit from object even in Python3 (i.e. not to leave the list of base classes empty), to make the code compatible with Python2, too.

Community
  • 1
  • 1
Piotr Ćwiek
  • 1,580
  • 13
  • 19