__name__ == “__main__” in Python

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s