Sunday, October 18, 2015

__main__

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.