What myth behind it if __name__ == ‘__main__’

Share Your Love

The line if __name__ == '__main__': is a common Python idiom used to check whether the current module is being run as the main program or if it is being imported as a module into another program.

When a Python module is run directly, its __name__ attribute is set to '__main__'. On the other hand, if the module is imported into another program, its __name__ attribute is set to the name of the module.

By using if __name__ == '__main__':, you can specify certain codes to run only when the module is run directly as the main program and not when it is imported as a module.

Here’s an example to illustrate the usage:

def some_function():
    # Code for the function

def main():
    # Code for the main program

if __name__ == '__main__':

In this example, if the module is run directly, the main() function will be executed. However, if the module is imported into another program, the main() function will not be automatically executed. This allows the module to be used as a library of functions that can be imported and used by other programs without executing the main program logic.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter