Python Splitting Code Into Modules
A module is a Python file that holds functions for one job. Splitting code into modules keeps each file short and focused.
The helper file first
The program writes greeter.py first. The import then brings its hello function in.
with open("greeter.py", "w") as f:
f.write("def hello(name):\n return \"Hello, \" + name\n")
import greeter
print(greeter.hello("Ada"))Two functions, one file
One module can hold many functions. Both are called with the module name in front.
with open("greeter.py", "w") as f:
f.write("def hello(name):\n return \"Hello, \" + name\n\ndef bye(name):\n return \"Goodbye, \" + name\n")
import greeter
print(greeter.hello("Ada"))
print(greeter.bye("Ada"))Import under a short name
as lets the import use a short name instead. The calls then use that short name.
with open("greeter.py", "w") as f:
f.write("def hello(name):\n return \"Hello, \" + name\n")
import greeter as g
print(g.hello("Bob"))Example
with open("calc.py", "w") as f:
f.write("def add(a, b):\n return a + b\n\ndef double(n):\n return n * 2\n")
import calc
prices = [5, 10, 15]
total = 0
for price in prices:
total = calc.add(total, price)
print("Total:", total)
print("Doubled:", calc.double(total))Key points
- Module: a Python file that holds code for one job
- Use import to bring a module's functions into another file
- Write the helper file first, then import it in the main file
- A module name is the file name without .py
- Use module.function() to call a function from a module
- A module can hold many functions, and each one stays in one place
- Split a file when one file holds two different jobs
In this example, the program writes calc.py first, with add and double inside. The import brings both functions in. The loop adds each price to the total with calc.add. The closing lines print the total first, then its double. The two numbers prove the split worked: the main file did the loop, and the helper file did the maths.
Note
The import works because the helper file sits in the same folder as the main program.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does import greeter do?