I recently asked a question on Twitter about whether I should show modern Python 3 code with classes that inherit from
object or not. For example:
class Spam(object): def yow(self): print('Yow!')
Overall, the responses tended towards the negative. “Just let Python 2 die already!” Given the hostility and upon further pondering, I think I’m going to go ahead and keep the
object in there. Let me explain…
First, by keeping it, you get a uniformity in syntax. All classes inherit from “something.” If you can’t think of something, use
object. Just do it.
Second, all classes inherit from
object anyways even if you don’t specify it. You’ll see this if you look at things like the MRO:
class Spam: def yow(self): print('Yow') >>> Spam.__mro__ (<class '__main__.Spam'>, <class 'object'>) >>>
The curious developer will start to ask questions… why is
object implicitly inserted in there? I didn’t inherit from object. Well, yes, you did. If you write
class Spam(object), it becomes a lot more explicit. Of course you inherited from
object–just look at the code. A hollow voice says “explicit is better than implicit.”
There’s also certain symmetry if you start using metaclasses. The
object classes go together as a pair. If you make a new metaclass, it’s common to make a new pairing like this:
class mytype(type): ... class myobject(metaclass=mytype): pass
You then define classes using:
class Spam(myobject): ...
So, classes always inherit from something. Usually it’s
object. Don’t ask questions–it all makes perfect sense. Just write it down.