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

I think the people replying "explicit is better than implicit" are cargo culting, there are quite a few areas where Python was more than happy to add a bit of magic to make the language smoother to use. Besides `if __name__ == "__main__"` is hardly explicit if you're not familiar with the idiom (what's `__name__` exactly? Is it the file name? The process name? When is and isn't it set to `__main__`?).

I can think of a real problem with your approach however: in languages with a main function you usually can't have top level statements, only declarations. So in C if you write at the top level `while (1) { printf("Hi\n"); }` you get a compilation error. Now as compilers get smarter you can get constexprs in some languages but it's still very specific and entirely static. I guess you could also mention global constructors, but that generally comes with severe caveats and should be used very carefully.

Python on the other hand treats top level code like anything else. That's why the `if __name__ == "__main__"` pattern even works in the first place. Having a real-looking main function would send the wrong message IMO, because it would make people that it's the real entry point of the program which it's not, in Python the entry point is the first line of the file being executed, end of story.

I do think that Python would benefit having a clearer and more explicitly named helper function or variable for this use case however, something like "if this_file_is_executed()" or something like that. At least this way you'd know what the code is doing instead of this awkward anti-pattern being used these days. But of course by now it's probably not worth changing.



You only need the __main__ magic if you want a python file to be both a module and an executable script. This is a moderately advanced requirement. Beginners will tend to write scripts OR importable modules.


For debugging-in-REPL purposes it's often very convenient to have it both ways. I was taught as a beginner to treat it as idiomatic boilerplate for that reason--no harm in having it, and there when you need it. Then you can just import your script and ad hoc test your functions.

It's a good technique prior to introducing formal unit testing (and even then, supplemental ad hoc has advantages).




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

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

Search: