DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for The if __name__ == "__main__" conditional in python
Osinachi Chukwujama
Osinachi Chukwujama

Posted on

The if __name__ == "__main__" conditional in python

TL;DR

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.

module.py

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

if __name__ == "__main__":
  print(func1())

# When this module (or script) is run this would be the output
I am module.py
The first function was called
Enter fullscreen mode Exit fullscreen mode

script.py

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

# When this script is run, this would be the output
I am module.py
I would be printed after 'I am module.py'
# Note, func1 wasn't called
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.