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

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 module, as well as a standalone program. We can run mymath standalone by doing this:
$ python mymath.py
test: square(42) == 1764
But we can also use mymath.py as a module; let’s see what happens when we run mygame.py:
$ python mygame.py
this is mygame.
289
Notice that here we don’t see the ‘test’ line that mymath.py 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.
[From a post to Python Tutor by Danny Yoo]
CATEGORY: tutor

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
In the case of your script, let's assume that it's executing as the main function, e.g. you said something like
python threading_example.py
on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.
One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
See this page for some extra details.

Comments

Popular Posts