Python code organization

Python Functions and Modules

Use Python functions and modules to split long scripts into reusable units, pass clear inputs, and create a safe main entry point for imports.

How this page is maintained

Written for learners, checked against the sources below, and reviewed every year. Last reviewed July 22, 2026.

Short answer

Use functions to isolate one task with clear inputs and outputs, then group related functions into modules. This makes scripts easier to test, reuse, and review than one long file with shared mutable state.

  • Write small functions with names that describe one action.
  • Pass values as parameters instead of relying on global variables.
  • Use a main entry block so modules can be imported safely in tests.

Design function boundaries around data flow

A strong function boundary states what goes in and what comes out. For an order report workflow, one function can parse rows, another can compute metrics, and a third can format output.

Type hints improve readability and editor support. They also reduce mistakes when scripts evolve into larger tools.

Split reusable logic into modules

A module is a Python file that can be imported by other files. Put reusable helpers into a module and keep command-line orchestration in a thin run script.

  • Use from package.module import name only for stable public functions.
  • Avoid wildcard imports because they hide where names come from.
  • Use if __name__ == "__main__" for script-only behavior.

Refactor one script into modules

An operations script currently loads CSV files, computes KPIs, and writes output in one file.

  1. Create metrics.py with functions that calculate refund rate and average order value.
  2. Create io_utils.py with functions for reading CSV files and writing summaries.
  3. Keep run_report.py as the entry point that calls those functions in order.
Result: The report workflow is now reusable, and each part can be imported directly in tests.

Common mistakes

  • Creating giant functions that mix loading, transforming, and output logic.
  • Mutating global variables that multiple functions depend on.
  • Importing a script file that executes work at import time.
  • Using unclear names like do_stuff for core business logic.

Try one

Why is if __name__ == "__main__" useful in a module that also has reusable functions?

It prevents script-only code from running when the module is imported by tests or other modules.

Sources

Learn this with a tutor

Tell LearnLive what you already know and what you need to do with functions and modules.

Build this course