Packages and Module Execution
Lesson 29 of 48 in Coddy's Python for Go Developers course.
Go packages group files and expose capitalized identifiers; package initialization runs before main. A Python module is commonly one .py file. Importing it executes its top-level code on the first import in a process, then ordinary imports use the cached module. Definitions and imports still execute under import, but an if __name__ == "__main__" guard restricts the entry call to script execution. Python naming conventions do not enforce Go export visibility.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
func gcd(a, b int) int { for b != 0 { a, b = b, a%b }; return a }
// Inside main:
fmt.Println(gcd(12, 8))Python
def gcd(a, b):
while b:
a, b = b, a % b
return a
def main():
print(gcd(12, 8))
if __name__ == "__main__":
main()Porting trap
Keep input and printing inside main, not at unguarded module scope. Another module or the locked driver must be able to import your helper without consuming input. Use the standard-library math.gcd in the exercise; the short helper here illustrates the guard.
Challenge
BeginnerIn program.py import math and implement common_pack(a, b) returning math.gcd(a,b). Define main() outside the guard; it reads two nonnegative integers and prints their gcd. Zero paired with a number yields that number; two zeros yield zero. Call main() only under if __name__ == "__main__":. Like Go package initialization, Python module import can run code; this module must neither read nor print during import. Put input/output in the guarded main call. The locked driver consumes a script/import mode first. In script mode your main reads the two numbers. In import mode the driver imports program, rejects input/output during import, then reads a count and that many integer pairs and prints helper results. Your code must not read the mode or helper-call count.
Editable files: program.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler