The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

What is ‘if __name__ == “__main__”‘ for?

Posted by jpluimers on 2019/08/14

One of the things when I learned Python was that in some scripts I found a block starting with a statement like this:

if __name__ == '__main__':

It looked like an idiom to me, and indeed it is: [WayBack] What is ‘if name == “main“‘ for?.

It allows a file to be both used as “main” standalone program file and a module. That section of code will not be executed if it is loaded as a module.

Part of the idiom is also to put your code in a separate method so this block is as short as possible.

if __name__ == '__main__':
main()

Via: [WayBack] Why is Python running my module when I import it, and how do I stop it? (thanks user166390 and Jeremy Banks for the answers there)

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.