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

34. Python Project Workspace · Choose What Runs on Import

Guard a command-line entry point so other modules can import its functions quietly.

Lesson files · lessons/modules-and-workspaces/start-only-when-run

Before you start
- Import a function from a neighbouring Python file.
- Put statements in an if block and trace when they run.

By the end
- Guard the startup call so it runs when Python starts the file directly.
- Use the preview and run modes to show that the same file can supply a function or start a program.

Where you can use it
Make a badge tool that people can launch directly and that a test can import just to use its label function.

Python sets __name__ to "__main__" for the file it starts as the program. When another file imports it, __name__ holds the module name. Python still runs the top-level code on first import, including function definitions. Put the call to main() under if __name__ == "__main__". The function stays available to other files, and the guard makes the startup call happen only when this file is the entry point.

Predict
What value does the import give room_status.__name__?
- __main__
- room_status

Worked example (example.py)

files = {
    "room_status.py": '''def main():
    print("Room status is ready.")


if __name__ == "__main__":
    main()
''',
    "main.py": '''import room_status

print(room_status.__name__)
''',
}

# 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
room_status

Add a main guard inside badge_card.py around the startup call. Studio’s preview mode imports badge and prints the label for the next input line. Its run mode starts badge_card.py directly and should print Ready to print badges.

Starter program (starter.py)

files = {
    "badge_card.py": '''def badge(name):
    return f"Badge for {name}."


def main():
    print("Ready to print badges.")


main()
''',
    "preview_badge.py": '''from badge_card import badge

print(badge(input()))
''',
}

# 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)

if input() == "preview":
    run_project(files, "preview_badge.py")
else:
    run_project(files, "badge_card.py")


Starter input
preview
Nia

Hint
Indent main() under the guard. Keep def main() at the top level of badge_card.py.

Case 1. Try the sample
Input
preview
Nia
Expected output
Badge for Nia.

Case 2. Start the script directly
Input
run
Expected output
Ready to print badges.

Case 3. Import a badge for a different name
Input
preview
Science Club
Expected output
Badge for Science Club.

Stretch
Add an input call inside main and check which mode now reads an extra value.

Reflect
Why would a test that imports this file benefit from the guard?

Check your prediction
room_status Python loads room_status.py by its module name here.
