Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 36 / 101

Stop the import spaghetti.

Separate reusable code from the script that starts your application.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Importing a module executes its top-level statements. That makes import-time side effects surprising: a function library should not unexpectedly start a server or overwrite files. Keep definitions reusable and place application startup behind a main function guarded by __name__ == "__main__". A package groups related modules; an explicit public interface limits the coupling between those modules.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

package_boundaries.py
def format_report(count):
    return f"{count} tasks ready"

def main():
    print(format_report(3))

if __name__ == "__main__":
    main()
↳ EXPECTED OUTPUT
3 tasks ready

03 Under the hood

  1. 1

    Running the file as a script gives its module the special name __main__. Importing it normally gives it its import name instead.

  2. 2

    The guard calls main only for script execution. Another module can import format_report without printing the startup report.

  3. 3

    For a package, python -m package.module gives Python the package context needed for its imports. Keep configuration loading and external connections in an entry point rather than a module body.

04 Your turn, builder

A SMALL MISSION

Create a main function that calls a reusable square function, while keeping import-time execution quiet.

Reveal one possible solution +
one_possible_solution.py
def square(value):
    return value * value

def main():
    print(square(7))

if __name__ == "__main__":
    main()

05 Check your signal

QUICK SIGNAL CHECK

When does the main guard run its body?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.