Stop the import spaghetti.
Separate reusable code from the script that starts your application.
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.
def format_report(count):
return f"{count} tasks ready"
def main():
print(format_report(3))
if __name__ == "__main__":
main()3 tasks ready
03 Under the hood
- 1
Running the file as a script gives its module the special name __main__. Importing it normally gives it its import name instead.
- 2
The guard calls main only for script execution. Another module can import format_report without printing the startup report.
- 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
Create a main function that calls a reusable square function, while keeping import-time execution quiet.
Reveal one possible solution +
def square(value):
return value * value
def main():
print(square(7))
if __name__ == "__main__":
main()05 Check your signal
When does the main guard run its body?
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 ↗.