How about some syntactic sugar for " __name__ == '__main__' "?
marko at pacujo.net
Wed Nov 12 22:52:41 CET 2014
John Ladasky <john_ladasky at sbcglobal.net>:
> I find myself bothered by the programming idiom that we use to
> determine whether a module is being executed or merely imported:
> "if __name__ == '__main__':"
I find the idiom cute and loveably silly. A typing tongue twister of
sorts. That boilerplate is far less cumbersome than, say, in Java.
> Myself, I've been programming in Python for a decade, and I still
> haven't dug very deeply into what exactly __name__ means or does.
The idiom allows you to include a main function in auxiliary modules.
When imported, the module acts as a library. When executed, it acts as a
command. I have done this a couple of times IRL.
> I would like to start a discussion about whether Python should include
> a function which executes this evaluation, and hides all of the
> unfriendly dunderish details.
Probably not. Idioms are important in that they are immediately spotted
by a casual reader of the code. However ugly you consider those two
lines, it will not waste a measurable amount of your precious time to
begin your brand new project by typing:
if __name__ == "__main__":
Yes, I always type those in again. I don't copy them over as I do, say,
Java main programs or static HTML pages.
More information about the Python-list