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__'. keep a close eye on line 10
output of 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 ( importing the “theo” module

When we run we get this:

output of

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__': 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 again: nothing has changed here

And the output:

lines 7 and 8 were not executed

Published in Today I Learned