5

I've fully graduated from writing scripts to writing modules. Now that I have a module full of functions, I'm not quite sure if I should order them in some way.

Alphabetical seems to make sense to me, but I wanted to see if there were others schools of thought on how they should be ordered in a module. Maybe try to approximate the flow of the code or some other method?

I did some searching on this and didn't really find anything, except for that functions need to be defined before calling them, which isn't really relevant to my question.

Thanks for any thoughts people can provide!

2
  • Personally, I group them by functionality and relationship with one another, in order to avoid scrolling like a madman. The same goes for classes. In case you have a flat list of parithetic functions, maybe in a library module, yes, you could in principle order them alphabetically (dunno if there's a PEP about this) Commented Sep 27, 2015 at 21:50
  • There's no really agreed upon way. Private/helper functions at the top, that's about it. Ideally, you're modules should be small/short enough such that the ordering of the functions doesn't really matter. If your file has so many functions/lines that the ordering of them is affecting you, then the module is probably responsible for too much. Commented Sep 27, 2015 at 21:52

1 Answer 1

6

Code should be made to be easily readable by a human; Readability counts (from The Zen of Python).

Stick to the conventions of PEP-8, unless you have good reason not to do so.

My suggestion would be to start with the main parts of the module in a sequence that makes sense for this particular module. Helper functions and classes go below that in a top-down fashion.

Modern editors are quite capable of finding function or method definitions in code, so the precise sequence under the top level doesn't matter as much as they used to.

If your editor supports it consider using folding.

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

1 Comment

One should also Package larger projects. Don't just pack all your modules into one directory for the sake of convenience.

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.