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.

Latest comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.