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:

$ cat mymath.py
def square(x):
    return x * x

if __name__ == '__main__':
    print "test: square(42) ==", square(42)


$ cat mygame.py
import mymath

print "this is mygame."
print mymath.square(17)

In this example, we’ve written mymath.py to be both used as a utility modul