Python Tutorial / Create Modules and Split Code with import

A module is a reusable unit of Python code, often starting as one .py file. import locates and initializes a module rather than simply copying its text, so file locations and top-level executable statements matter.

Separate calculation from the application

Place the reusable calculation in expense_math.py and the calling code in app.py in the same practice folder. Use underscores rather than hyphens in module names. Avoid json.py or csv.py because they can shadow standard-library modules.

import expense_math binds the module name, allowing expense_math.total. from expense_math import total binds the function name directly, which can be convenient but requires watching for naming collisions.

For the relevant APIs and platform requirements, see Create Modules and Split Code with import documentation.

Create both complete files

Contents of expense_math.py:

def total(amounts):
    return sum(amounts)

Contents of app.py:

import expense_math

print(expense_math.total([3500, 8000, 2500]))

From the folder containing both files, run:

python app.py

The result is 14000. This two-file example needs no third-party package. Keep both filenames exactly as shown so that module lookup can locate the helper.

Understand lookup and initialization

Module lookup depends on the execution mode, project structure and installed environment. For ModuleNotFoundError, inspect spelling, interpreter selection and folder layout before changing sys.path or copying source files into a global installation directory.

Top-level statements run during the first import. Putting input() or deletion at module level can therefore start an operation merely by importing it. Define reusable work in functions and invoke it through an explicit entry point. Imported modules are normally cached, so restart the process to check edited code.

Test reuse and avoid circular dependencies

  1. Change one amount in app.py and check that the same helper produces the changed total.
  2. Temporarily add a print outside the helper definition to observe import-time execution, then remove it.
  3. Explain why using json.py as an application filename can hide the standard JSON module.

Two modules that import each other can request names before initialization has finished. Move common logic to a third module or simplify the dependency direction. The package and entry-point example shows how to prevent accidental execution during import.