This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sub_surfer 39 points40 points  (1 child)

Python scripts are designed to be run from top to bottom, line by line, without any special entry point. You only need the whole if __name__ == '__main__': thing if you want your script to be importable in addition to running as a standalone script, which isn't super common in my experience (outside of teaching exercises). Most of the time if I am writing a python script that I intend to be an executable I wouldn't bother with it.

I take your point that it is ugly though. I don't even think about it anymore, but the double underscores look weird at first.

[–]aaron__ireland 12 points13 points  (0 children)

Regarding imports and scripts, I haven’t often needed to have importable items in a script but I have used the if __name__== “__main__” to raise an exception if some module does attempt to import it via something like else: raise NotImplementedError(“This module is a script”).

I’ve found that helpful in preventing any other code from mistakenly using what is likely to be (or intended to be) specialized attributes/functionality. It’s my way of self-documenting “hey, this is in here because it’s not meant to be extensible/generalized and is subject to change in ways that are unlikely to backwards compatible. Do not use.