Skip to main content

__name__ & Module Patterns

beginner12 min readLesson 37 of 169

Script or import? The __main__ guard and reusable module design.

Any .py file is a module. Create geometry.py:

PI_APPROX = 3.14159

def circle_area(r):
    return PI_APPROX * r * r

Now import geometry from a file in the same folder and call geometry.circle_area(2).

name: script or import?

Every module has a __name__. When run directly it is "__main__"; when imported it is the module's name. This powers the standard guard:

def main():
    print("running demo")

if __name__ == "__main__":
    main()

Import geometry and main() stays quiet; run python geometry.py and it prints. One file, two behaviors — reusable by others, runnable by you.