Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python source file organization

I'm starting a new Python project, and want to follow standard conventions as closely as possible. I've read that import statements should come first, for example. But I haven't found any conventions for things like putting all function definitions before or after all class definitions. Are there any conventions for things like this? Or does everyone typically just organize things like function and class definitions in whatever order seems to make sense?

like image 646
Dan Avatar asked Dec 13 '10 05:12

Dan


2 Answers

PEP8 is the Python style guide: http://www.python.org/dev/peps/pep-0008/

Imports come at the top of the file, though method-level imports are allowed.

There's no specific ordering to classes and functions. Use what makes sense.

like image 87
Adam Vandenberg Avatar answered Sep 22 '22 05:09

Adam Vandenberg


No, there's no convention for organization of functions and classes. However, there are some basic guidelines that will make your source flow better and make more sense to readers:

  • Document. Whatever you do, make sure that the uses (and in some cases, implementation) of classes and functions is described in plain english)
  • Group together things that are alike. Two functions that perform similar functions? Put them together.
  • Use common sense. If a class extends another, the base class should come first. If a function takes an instance of a class you defined, make sure the class definition comes first.

For examples on how this is done, look no further than the Python standard library. The source files from some of the modules should give you an idea how source is organized in Python.

like image 37
Rafe Kettler Avatar answered Sep 18 '22 05:09

Rafe Kettler