Modules, Imports and the Main Guard
As programs grow you split them into modules: separate .py files, each holding related functions. A file named geometry.py is a module called geometry, and another file imports it:
# geometry.py
def area(w, h):
return w * h
# main.py
import geometry
print(geometry.area(3, 4)) # 12
# or pull in just one name
from geometry import area
print(area(3, 4))This keeps each file focused and lets you reuse code across projects. A package is just a folder of modules.
The __main__ guard
When Python runs a file directly, it sets the special variable __name__ to the string "__main__". When the same file is imported, __name__ is the module's name instead. That difference powers a very common pattern:
def area(w, h):
return w * h
if __name__ == "__main__":
# only runs when you execute this file directly,
# NOT when another file imports it
print(area(3, 4))The guard lets a file be both an importable library and a runnable script, without the demo code firing on import. We grade this lesson on a normal function, since the grader runs a single snippet, but the pattern is essential once you have many files.
Imagine a small module. Define a function circle_area(radius) that returns 3.14159 * radius * radius. Then add the if __name__ == "__main__": guard, and inside it set a variable demo to circle_area(2) (since this snippet runs directly, the guarded block will execute and demo will be defined).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.