Python — Organizing code across files
In Python, a module is a file that can define reusable functions. Importing a function from a neighbouring module lets the main script call it by name.
A simple example
Import one function
- Start with 9
- Do this Import and call isqrt
- Result 3
from math import isqrt
print(isqrt(9))
3
Share a function between source files
Python looks for boxes.py beside the entry script. Importing the module binds its function without running any example code, because the helper only defines the function.
A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
def remaining(capacity, used):
return capacity - used
from boxes import remaining
print(remaining(8, 3))
5
Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.
Try it yourself
Change the used count from 3 to 8 in the caller.
Check your answer
Running the same command prints 0. No change to the helper is needed.