Code

Who Is Running Me?

Every module has a built-in variable called __name__:

  • When you run a file directly (python compass.py), its __name__ is "__main__".
  • When it is imported (import compass), its __name__ is the module name, "compass".

That lets one file be both a reusable module and a runnable script. Put the "demo" code under a guard:

def heading(degrees):
    ...

if __name__ == "__main__":
    print("compass demo:", heading(95))   # only when run directly

Without the guard, everyone who imports your module would see the demo print, which is noisy and sometimes slow!

runpy.run_path("compass.py", run_name="__main__") runs a file as if you typed python compass.py. We use it below to test both ways.

Assignment

  1. In the compass.py text, move the demo print under an if __name__ == "__main__": guard, so import compass is quiet.
  2. At the very end of the main program, print(__name__) to see what your program is called.