Skip to content →

if __name__ == ‘__main__’ Explained

It’s very common to want to import functions and variables from modules without executing the source code that they came from. One way to do this is to add if __name__ == '__main__': before the section of the module you do not want to be executed if it’s being imported. This post attempts to explain why that commonly used conditional statement works.

The Python interpreter reads the source code of a module and executes everything in it from top to bottom. But before executing the code, it sets a few special variables, one of them is __name__. If the interpreter is running the file as the main program, it sets the __name__variable to '__main__'.

theo.py: keep a close eye on line 10
output of theo.py

theo.py was interpreted as the main program, so the value of __name__ was set to '__main__'.

Now let’s see what happens when we import this module (import_theo.py):

import_theo.py: importing the “theo” module

When we run import_theo.py we get this:

output of import_theo.py

Notice how __name__ was set to theo. This is because we imported the “theo” module; this is not our main program. The Python interpreter sets the __name__ variable within the imported module to it’s own name, in this case theo.

This behavior allows us to have control of what we want to execute when we a module is imported, if anything at all. To prevent execution from happening during import we can write a conditional statement using __name__ and '__main__':

theo.py(version 2)

Line 6 tells the interpreter to only execute lines 7 and 8 if the module is being ran as the main program, not if it’s being imported.

Let’s run import_theo.py again:

import_theo.py: nothing has changed here

And the output:

lines 7 and 8 were not executed

Published in Today I Learned