Viking's Website

What is 'if __name__ == "__main__"' for?

The if __name == \”\main__”: … trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let’s say that we have two files:

In this example, we’ve written to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this:

But we can also use as a module; let’s see what happens when we run

Notice that here we don’t see the ‘test’ line that had near the bottom of its code. That’s because, in this context, mymath is not the main program. That’s what the if __name == \”\main__”: … trick is used for.