Modules Versus Utility Classes
Lesson 29 of 48 in Coddy's Python for Java Developers course.
Put reusable definitions in a Python module, which is ordinarily a .py file. Java import resolves type names; Python import loads and executes module-level statements on first import in an interpreter, then normally reuses the cached module. A main guard allows script-only input/output while preserving importable helpers. Running a file as the main program gives it __name__ == "__main__"; importing program.py ordinarily gives it __name__ == "program". Keep helper definitions outside the guard so importers can use them.
Java: complete Main.java
public class Main {
static int twice(int x) { return x * 2; }
public static void main(String[] args) { System.out.println(twice(4)); }
}Python
def twice(x):
return x * 2
def main():
print(twice(4))
if __name__ == "__main__":
main()Watch the difference
The guard is not a Java main signature. Code outside it still runs while importing, including top-level input or print calls. The supplied driver demonstrates both execution modes without requiring package installation.
Practice
Apply this comparison in the task below. 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.
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__":. Unlike Java import name resolution, importing a Python file executes top-level statements, so importing must neither read nor print. 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 Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler