6

In my research I found that in Python 3 these three types of class definition are synonymous:

class MyClass:
    pass

class MyClass():
    pass

class MyClass(object):
    pass

However, I was not able to find out which way is recommended. Which one should I use as a best practice?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Tim Keller
  • 389
  • 1
  • 12
  • One note: In my case the code will only run with python3 in mind, so backwards compatibility is explicitly not wanted. – Tim Keller Aug 23 '17 at 08:34

2 Answers2

6

I would say: Use the third option:

class MyClass(object):
    pass

It explicitly mentions that you want to subclass object (and doesn't the Zen of Python mention: "Explicit is better than implicit.") and you don't run into nasty errors in case you (or someone else) ever run the code in Python 2 where these statements are different.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
4

In Python 2, there's 2 types of classes. To use the new-style, you have to inherit explicitly from object. If not, the old-style implementation is used.

In Python 3, all classes extend object implicitly, whether you say so yourself or not.

You probably will want to use the new-style class anyway but if you code is supposed to work with both python 2 and 3 you'll have to explicitly inherit from object:

class Foo(object):
    pass 

To jump on the other answer, yes the Zen of Python state that

Explicit is better than implicit.

I think this mean we should avoid possible confusion in code like we should in language in general, remember code is communication.

If you only work with python 3, and your code/project explicitly state that, there is no possible confusion, all class without explicit inheritance automatically inherit from object. If for some obscure reason the base class change in the future (let's imagine from object to Object), the same code will work. And the Zen of Python also says that

Simple is better than complex.

(of course complex is quite an overstatement in this example but still...)

So again if you code only support python3, you should use the simplest form:

class Foo:
    pass

The form with just () is quite useless since it doesn't give any valuable information.

lee-pai-long
  • 2,147
  • 17
  • 18
  • Another argument for the usage of the simplest form might be that it is quite python specific to explicitly inherit from a default object. As far as I know it is not common, e.g. in C++ or Java. – Tim Keller Aug 24 '17 at 14:08
  • @TimKeller that's true, at the end of the day inheriting from object is a implementation detail and that convention that a class implicitly inherit from it is quite clear for everyone to use. – lee-pai-long Aug 24 '17 at 14:25