Python name == 'main'
def main():
# program code
if __name__ == "__main__":
main()
What is name?
Python automatically assigns the built-in variable __name__ to every module before running any of its code -- when you execute a file directly with 'python script.py', that file's __name__ is set to the special string __main__.
Example: What is name?
print(__name__)
The Main Guard
Wrapping your script's entry-point logic in 'if __name__ == "__main__":' means that code only runs when the file is executed directly, not when another file imports it -- this is the standard way to let a file be both a runnable script and a safely importable module.
Example: The Main Guard
def main():
print("Running main logic")
if __name__ == "__main__": # only runs when this file is executed directly
main()
Importing Modules
When a file is imported rather than run directly, Python sets its __name__ to the module's own name (e.g. mymodule) instead of __main__ -- printing __name__ from inside both an imported module and the script that imports it demonstrates this difference clearly.
Example: Importing Modules
# When this file is imported, __name__ becomes its module name
# instead of "__main__"
print(__name__)
Script vs Module
The main guard is what lets a single file define reusable functions and classes for other code to import, while also including a runnable demo or test block at the bottom that only fires when someone runs that file directly rather than importing it.
Example: Script vs Module
def greet():
print("Hello from a reusable function")
if __name__ == "__main__":
greet() # only runs when this file is executed directly
Best Practices
Keeping top-level code (code that isn't inside any function) to a minimum and moving your actual logic into functions called from within the main guard keeps variable names from leaking into the module's namespace and makes the file's behavior easier to reason about.
Example: Best Practices
def run():
print("Logic lives inside a function") # keeps names out of the module's top-level namespace
if __name__ == "__main__":
run()
- Writing
if __name__ == "main":instead of"__main__", so the block never runs. - Putting all the program code outside the guard, so importing the file also runs it.
- Forgetting the double underscores, as in
_name_, which raisesNameError.
- Modules organize code and are loaded with the
importstatement. - The standard library,
pip, and virtual environments provide and manage packages. - The
__name__ == __main__check separates running a file from importing it.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: