The if __name__ == "__main__" conditional in python

The if __name__ == "__main__" conditional in python


2 min read


When a module is imported into a script, the module's code is run when the script is run. This is useful for unit testing

Like, most programming languages, python has special variables. A peculiar special variable in python is the __name__ variable.

When you have a script that can act as both a module and a script, you'd probably need this conditional statement.

One thing about python modules is that if imported, into a script all the code in that module is run when the script is run.

print("I am")
def func1():
  return "The first function was called"

if __name__ == "__main__":

# When this module (or script) is run this would be the output
I am
The first function was called

import module
print("I would be printed after 'I am'")

# When this script is run, this would be the output
I am
I would be printed after 'I am'
# Note, func1 wasn't called

Now, let's assume we have a script with useful utility functions. We want to be able to test our script and also export it as a module. We would put our unit tests in the conditional if __name__ == "__main__"

Try this out yourself. Investigate it. Then learn about unit testing in python. Thanks for reading.