What does __name__ == "__main__" mean?

When you run a python script directly (example: $ python script.py), you want to set a starting point of the script. Python scripts are interpreted from the first line, then goes to the second line and so on ...

import module

def my_function():
  # code here

x = my_function()

But you want to make your code more structured, so you come up with this:

import module

def my_function():
  # code here

def main():
  x = my_function()

# the program starts from here
main()

This is good, but problem is, if you import the script from another script (from module import *), the main() function gets executed, but you may not want to do this. You want to call the main() function only when this script is exclusively executed. And you can do this using __name__ == "__main__".

import module

def my_function():
   # code here

def main():
   x = my_function()

# the program starts from here
if __name__ == "__main__":
   main()

Thus you can make your script to make it a reusable script (import from another script) and a standalone script as well.

Comments

Unknown said…
Thank you for clear discussion
jaskaran said…
Can you explain little bit more, I can not understand this :(


This is good, but problem is, if you import the script from another script (from module import *), the main() function gets executed, but you may not want to do this. You want to call the main() function only when this script is exclusively executed. And you can do this using __name__ == "__main__".

Tamim Shahriar said…
Say you have a script named math.py that has a function named add(x, y). Now in another python file if you need to use this add function, you need to import math. But in your math.py file, if there is some test code like print add(5, 5), it will also get executed. So you should write the test code in math.py file inside the if block (if __name__ == "__main__"). So only when you run math.py file exclusively, it will run, otherwise not.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code