Python – a good way to order methods in a Python class


I want to order methods in a Python class but I don't know what is the correct order.

When I extract methods in Eclipse with PyDev, Eclipse puts the extracted method on top of the modified method. But this puts the lower level details before the higher level details. According to Uncle Bob I should do the opposite so that my code reads like the headlines of a newspaper. When I program Java I just follow his advice.

What is the best practice for Python?

Best Solution

As others have pointed out, there is no right way to order your methods. Maybe a PEP suggestion would be useful, but anyway. Let me try to approach your question as objectively as possible.

  • Interfaces first: Public methods and Python magic functions define the interface of the class. Most of the time, you and other developers want to use a class rather than change it. Thus they will be interested in the interface of that class. Putting it first in the source code avoids scrolling through implementation details you don't care about.

  • Properties, magic methods, public methods: It's hard to define the best order between those three, which are all part of the interface of the class. As @EthanFurman says, it's most important to stick with one system for the whole project. Generally, people expect __init__() to the best first function in the class so I follow up with the other magic methods right below.

  • Reading order: Basically, there are two ways to tell a story: Bottom-up or top-down. By putting high-level functions first, a developer can get a rough understanding of the class by reading the first couple of lines. Otherwise, one would have to read the whole class in order to get any understanding of the class and most developers don't have the time for that. As a rule of thumb, put methods above all methods called from their body.

  • Class methods and static methods: Usually, this is implied by the reading order explained above. Normal methods can call all methods times and thus come first. Class methods can only call class methods and static methods and come next. Static methods cannot call other methods of the class and come last.

Hope this helps. Most of these rules are not Python-specific by the way. I'm not aware of a language that enforces method order but if so, it would be quite interesting and please comment.