Packages and the Main Guard
Scenario: Importing a useful function unexpectedly runs the module's command-line program.
New words, in plain English
- Package - a directory grouping related Python modules
__name__- a special name identifying how a module was loaded- Main guard - an if statement that runs CLI code only for direct execution
A package commonly includes __init__.py. Relative imports connect sibling modules. When a file is run directly, __name__ is "__main__"; when imported, it is the module name.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
def main():
print("running CLI")
if __name__ == "__main__":
main()
Tip: Keep import-time behavior small and predictable.
Goal: Practice this idea in the py-modules-import challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.