Modules and the Main Guard
Lesson 29 of 48 in Coddy's Python for Rust Developers course.
Rust mod declares modules and use brings paths into scope without executing a Python-style module body. Python imports load and execute module top-level code, normally once per module per process, then cache the module. Put reusable functions in separate files and import them without the .py suffix. The guard if __name__ == "__main__": runs demonstration code only when the file is executed as the main program. Imports should not unexpectedly read input or print.
Rust excerpt inside main
mod arithmetic {
pub fn twice(x: i32) -> i32 { x * 2 }
}
println!("{}", arithmetic::twice(4));Python
def twice(x):
return x * 2
def main():
print(twice(4))
if __name__ == "__main__":
main()Porting trap
In these tasks driver.py is the only marked entry point. An editable main.py may contain helper logic but does not become the runner entry just because of its name.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerWrite a complete program with import math, a function common_pack(a, b) returning math.gcd(a, b), and main() that reads two nonnegative integers on separate lines and prints the result. math.gcd returns the greatest common divisor; it returns the other argument when one is zero and 0 when both are zero. Call main() only under if __name__ == "__main__":. Importing the definitions must not read input or print.
The locked test harness consumes a first line containing script or import; your program must not read or handle that mode. In script mode, the harness sets __name__ to "__main__", then your program reads and prints exactly as described above. In import mode, it imports program.py as module program, so that file sees __name__ == "program" and rejects any attempted input or printing while your definitions load. After loading, it restores normal input and output, reads a helper-call count and that many lines of two nonnegative integers, calls your reusable helper for each pair, and prints the helper result on one line per pair. Keep both the helper and main defined outside the main guard. You only submit the complete Python program; the harness is provided and locked.
Edit program.py. The locked driver.py tests both running it as a script and importing it as a module. The driver handles the test-mode input; your program reads only the data described above.
Try it yourself
import importlib as _coddy_importlib
import runpy as _coddy_runpy
import builtins as _coddy_builtins
_coddy_input = _coddy_builtins.input
_coddy_print = _coddy_builtins.print
_coddy_mode = _coddy_input()
_coddy_import_io = []
def _coddy_forbidden_input(*args, **kwargs):
_coddy_import_io.append("input")
raise AssertionError("input during module loading")
def _coddy_forbidden_print(*args, **kwargs):
_coddy_import_io.append("print")
raise AssertionError("print during module loading")
if _coddy_mode == "script":
__name__ = "__main__"
elif _coddy_mode == "import":
__name__ = "course_module"
_coddy_builtins.input = _coddy_forbidden_input
_coddy_builtins.print = _coddy_forbidden_print
else:
raise AssertionError("invalid harness mode")
if _coddy_mode == "script":
_coddy_namespace = _coddy_runpy.run_module("program", run_name="__main__")
else:
_coddy_namespace = vars(_coddy_importlib.import_module("program"))
common_pack = _coddy_namespace['common_pack']
main = _coddy_namespace['main']
_coddy_builtins.input = _coddy_input
_coddy_builtins.print = _coddy_print
if _coddy_import_io:
raise AssertionError("module loading attempted input or output")
if _coddy_mode == "import":
if not callable(main):
raise AssertionError("main must be a callable function")
_coddy_count = int(_coddy_input())
for _coddy_index in range(_coddy_count):
_coddy_left, _coddy_right = _coddy_input().split()
_coddy_result = common_pack(int(_coddy_left), int(_coddy_right))
if type(_coddy_result) is not int:
raise AssertionError("common_pack must return an integer")
_coddy_print(_coddy_result)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler