Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"if name == “__main__” isn't magic, it serves a purpose. Sometimes name == “__main__” and sometimes it doesn't, and I want to specify different behavior in different cases.

Here, name is the name of the module. When the module is run by itself, this is the same as __main__, in which case I want the things specified by the if to run right away. This could be calling a main function, but a lot of times it's just is some tests or examples.

When the module is imported into another file, it's name is not the same as __main__. In this case I usually only want things in it to do stuff when they are called by the other file.

This doesn't have anything to do with a function literally called "main" though.

  if __name__ == "__main__":
    main()
Is a common idiom, but there's no connection between the two uses of the word main.



Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: