2

For a class definition with no inheritance, is there any difference or stylistic preference between:

class M:
    pass

and

class M():
    pass

?

I couldn't find it mentioned in PEP8.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • If it's not in PEP8, another good place to get advice is by looking at the standard library – John La Rooy Nov 25 '13 at 22:58
  • FWIW, I still fall into the camp of always inherit from `object` ... even though it is pretty meaningless in python3.x... – mgilson Nov 25 '13 at 22:58
  • @mgilson: Since they rewrote the tutorial to remove all the `(object)` bases at some point, I think it's no longer tenable to say "everyone should always inherit from `object`. It _is_ still perfectly reasonable to always do so _yourself_, but that still leaves open the question of "when people don't do so, how should they spell it?", which is what the OP's asking. – abarnert Nov 25 '13 at 23:01
  • @abarnert -- Yeah, I know. That's why I prefixed my comment with a FWIW and a statement clearly indicating that it is my opinion not to spell it without the `object` :-). I'm still a few years away from that I think :). But, for people writing py3k only code in *all* of their projects, I suppose that I agree with your answer. – mgilson Nov 25 '13 at 23:03

1 Answers1

7

It's not in PEP 8 because in the early days of Python 3, Guido suggested that everyone should be explicitly inheriting from object during the transition period. Possibly this should be updated…

However, if you look at all of the examples in the documentation that don't use class M(object):, they all use the first format, class M:.

For example, see Class Definition Syntax, Class Objects, and all of the following sections in the tutorial. (And note that the tutorial doesn't even explain that you can use zero base classes inside the parentheses.)

(Plus, at least to me, the second format implies that you're explicitly trying to inherit from nothing, which is misleading, while the first implies that you're just doing whatever the default is.)

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 1
    +1. PEP8 was actually written with Python 2 in mind when there was an [actual difference](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python) between inheriting explicitely from `object` and specifying nothing. I’d also agree that empty parentheses would make it a bit ambigous if it’s inheriting from object or not (although it always will). So the first way would be preferred. – poke Nov 25 '13 at 23:02
  • @poke: Great addition. But PEP8 is supposed to evolve with the language (it was most recently revised 1 Aug 2013), so maybe it should cover this case nowadays. But that's something to be debated on the bug tracker or one of the lists, if someone cares strongly enough to want it changed. – abarnert Nov 26 '13 at 01:52