Organizing Python code
Python programs should be beautiful. To that end, the language has few syntactic overheads; we should be able to write short scripts without unpleasant boilerplate. The principle is sometimes articulated as Simple things should be simple. The "Hello World" script really is a single line of code that uses the print()
function.
A more complex file will generally have a few major sections:
- A
!#
line, often#!/usr/bin/env python3
. - A docstring comment explaining what the module does.
- The function or class definitions. We often group multiple functions and classes into a single module. The module is the proper unit of reuse in Python.
- If the module can be run as a main script, we'll include an
if __name__ == "__main__":
section that defines the file's behavior when run as the main script.
Many applications are too complex for a single file. When designing larger applications, the Pythonic ideal is to keep the resulting structure as flat as possible...