← Back to course
Code Crew G6+ / Week 06 / Friday
5/6
Week 06 Β· Functions and modules

Friday

Your own module
// Name a job once, use it everywhere
⏱ about 30 min

Friday: Your own module

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 of your own

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

Importing it

# 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
MODULES
  • Read the question.
  • Tap your answer.
When trip_planner.py runs, does Testing crew_tools appear?
Where must crew_tools.py be saved for import crew_tools to work?
The user types 50 into trip_planner.py. What number does the Fuel needed line show?
WHY THIS EXERCISEfuel_needed(50.0) is 50.0 times 3 plus 10, which is 160.0.
At your computer
1. Type crew_tools.py, save it in your mission folder and run it. Check the three test lines.
2. Make a new file, type trip_planner.py and save it in the same folder.
3. Run trip_planner.py and type 100. Check that Testing crew_tools does not appear.
4. Add a third function to crew_tools.py, save it, and call it from trip_planner.py.
If you see ModuleNotFoundError, check that both files are saved in the same folder.

Practice: two more ways to import

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))
IMPORT STYLES
  • Read the question.
  • Tap your answer.
After from crew_tools import to_minutes, how do you call it?
After import crew_tools as ct, which call works?
Why does quick_plan.py not show Testing crew_tools?
What does to_minutes(3) show?
What does ct.fuel_needed(10) show?
StatementTrue 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.?
WHY THIS EXERCISEPython finds crew_tools.py from import crew_tools, as long as it sits in the same 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.

← Thursday