──────────────────────────────────────

33. Python Project Workspace · Import a Function from Another File

Keep a calculation or formatting rule in one file and use it from another.

Lesson files · lessons/modules-and-workspaces/import-your-module

Before you start
- Define a function that returns formatted text.
- Call an imported tool such as Path from pathlib.

By the end
- Import room_label from a neighbouring Python file and call it from main.py.
- Identify which file owns the label format and which file reads the inputs.

Where you can use it
Keep room-label formatting in one Python file so both a check-in script and a door-sign script can import it.

A module can be a Python file. When two files are beside each other, main.py can use from room_labels import room_label to make the room_label function available. The module name omits .py. A regular package is a folder of modules with an __init__.py file. This lesson uses two modules in the same folder. In Studio, the triple-quoted strings hold each file’s source. The supplied runner creates the files for this run, then starts main.py. On your own computer, save the strings’ contents as separate files in one folder.

Predict
Which file contains the calculation?
- ticket_price.py
- main.py

Worked example (example.py)

files = {
    "ticket_price.py": '''def tickets_total(count):
    return 3 * count
''',
    "main.py": '''from ticket_price import tickets_total

print(tickets_total(4))
''',
}

# Studio makes the files available for this run.
from pathlib import Path
from runpy import run_path
from tempfile import TemporaryDirectory
import sys


def run_project(files, entry, args=()):
    with TemporaryDirectory() as folder:
        for filename, source in files.items():
            Path(folder, filename).write_text(source, encoding="utf-8")
        saved_args = sys.argv
        sys.argv = [entry, *args]
        sys.path.insert(0, folder)
        try:
            run_path(str(Path(folder, entry)), run_name="__main__")
        finally:
            sys.argv = saved_args
            sys.path.remove(folder)
            for filename in files:
                sys.modules.pop(Path(filename).stem, None)

run_project(files, "main.py")


Example result
12

In the source for main.py, import room_label from room_labels. Keep the starter’s room and floor inputs. Call room_label with those values and print its return value.

Starter program (starter.py)

files = {
    "room_labels.py": '''def room_label(name, floor):
    return f"{name} (floor {floor})"
''',
    "main.py": '''
room = input()
floor = int(input())
print(room)
''',
}

# Studio makes the files available for this run.
from pathlib import Path
from runpy import run_path
from tempfile import TemporaryDirectory
import sys


def run_project(files, entry, args=()):
    with TemporaryDirectory() as folder:
        for filename, source in files.items():
            Path(folder, filename).write_text(source, encoding="utf-8")
        saved_args = sys.argv
        sys.argv = [entry, *args]
        sys.path.insert(0, folder)
        try:
            run_path(str(Path(folder, entry)), run_name="__main__")
        finally:
            sys.argv = saved_args
            sys.path.remove(folder)
            for filename in files:
                sys.modules.pop(Path(filename).stem, None)

run_project(files, "main.py")


Starter input
Robotics Lab
2

Hint
Add from room_labels import room_label inside the main.py string, above both inputs.

Case 1. Try the sample
Input
Robotics Lab
2
Expected output
Robotics Lab (floor 2)

Case 2. Ground floor
Input
Hall
0
Expected output
Hall (floor 0)

Case 3. Another room
Input
Art Studio
3
Expected output
Art Studio (floor 3)

Stretch
Try import room_labels and call room_labels.room_label(room, floor).

Reflect
Which file would you edit to change every label that uses this rule?

Check your prediction
ticket_price.py The import lets main.py call the function defined in ticket_price.py.
