Definition
A module is simply a .py file. Any file can be imported by name, which lets you split a program across files. The check if __name__ == "__main__" runs code only when the file is run directly, and not when it's imported.
In simple words
Instead of one giant notebook, you keep maths notes in one file and chemistry in another, and open the one you need. The __name__ check says: run this part only if I'm the file you opened directly.
Why it matters
Every real project is split into modules. Without the __name__ check, importing a file would also run its demo code.
How it works
# shapes.py
PI = 3.14159
def circle_area(r):
return PI * r * r
if __name__ == "__main__":
print(circle_area(2)) # runs only for: python shapes.py
# main.py, in the same folder
import shapes
from shapes import circle_area
print(shapes.PI, circle_area(1))In code
print("This file's __name__ is:", __name__)
def main():
print("Running as the main program")
if __name__ == "__main__":
main()Output
This file's __name__ is: __main__ Running as the main program
Common mistakes
- Calling your file random.py, and then wondering why import random fails.
- Putting code that does work at the top level of a module, so it runs on import.
Check yourself
Summary
- A module is a .py file you can import.
- Use the __name__ check for code that shouldn't run on import.
- Don't name files after libraries.
Finished reading?
Sources: The Python Tutorial, python.org