6

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?

1
  • Thanks for the help. Both answers were good, so I tried voting up both, but it wouldn't let me. So I chose one of the answers as the best one, by flipping a coin. Commented Dec 13, 2010 at 20:39

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.