Rocket has written useful functions in three different programs this week. Now his trip planner needs two of them, and he is about to copy and paste them again.
"Wait," he says, hand frozen above the keyboard. "We said no more copying. So how do programs share?"
Raven thinks back to the countdown clock. "What do you notice about time.sleep?" she asks. "We did not write sleep ourselves. We imported a file that has it."
Nova displays two files side by side with a glowing thread between them. "I found a pattern," she says. "Any .py file can be a module. Put your tools in one file, and import it from another file in the same folder."
Rocket creates a new file called crew_tools.py.
A module is just a .py file. If crew_tools.py is in the same folder as your program, the line import crew_tools loads it. Then you use its functions with a dot, like crew_tools.fuel_needed(20).
The test lines at the bottom use a special check. __name__ is "__main__" only when you run that file directly. When another program imports it, the test lines are skipped.
# crew_tools.py
"""Small tools for Mission Control."""
def to_minutes(hours):
"""Turn hours into minutes."""
return hours * 60
def fuel_needed(distance, rate=3, reserve=10):
"""Fuel for a trip: distance times rate, plus a reserve."""
return distance * rate + reserve
if __name__ == "__main__":
print("Testing crew_tools")
print(to_minutes(2))
print(fuel_needed(20)) Running crew_tools.py on its own shows its test lines:
Testing crew_tools 120 70
# trip_planner.py
import crew_tools
distance = float(input("Distance in km: "))
print("Fuel needed:", crew_tools.fuel_needed(distance))
hours = distance / 50
print("Minutes at 50 km per hour:", crew_tools.to_minutes(hours)) Distance in km: 100 Fuel needed: 310.0 Minutes at 50 km per hour: 120.0
from crew_tools import to_minutes loads just that one function. You then call it without the module name and the dot.
import crew_tools as ct gives the module a short nickname, so you write ct.to_minutes(2).
# quick_plan.py from crew_tools import to_minutes import crew_tools as ct print(to_minutes(3)) print(ct.fuel_needed(10))
| Statement | True or false? |
|---|---|
| Any .py file can be imported as a module. | ? |
| The import line includes .py, like import crew_tools.py. | ? |
| The module file must be in the same folder for this kind of import. | ? |
| ModuleNotFoundError often means the file is in the wrong folder. | ? |
You built a module and imported it, just like the professionals do. Mission Log will use this trick for its tests in week 12. Tomorrow is a Crew Quest.