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 ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.