How about some syntactic sugar for " __name__ == '__main__' "?

Chris Kaynor ckaynor at
Wed Nov 12 22:33:51 CET 2014

On Wed, Nov 12, 2014 at 1:07 PM, Joel Goldstick <joel.goldstick at>

> On Wed, Nov 12, 2014 at 4:02 PM, John Ladasky
> <john_ladasky at> wrote:
> > I have taught Python to several students over the past few years.  As I
> have worked with my students, 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__':"
> >
> > The use of two dunder tokens -- one as a name in a namespace, and the
> other as a string, is intimidating.  It exposes too much of Python's guts.
> As such, I think that it is less Pythonic than we might want.  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.
> >
> > 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.  And if that's a good idea, I would invite a discussion
> of how, exactly, it should be implemented.  I'm nowhere near proposing a
> PEP, but that may come later.
> >
> > Thanks for your thoughts.
> How about a decorator?

A decorator is an interesting idea, and should be easy to implement (only
lightly tested):

def main(func):
    if func.__module__ == "__main__":
    return func # The return could be omitted to block the function from
being manually called after import.

Just decorate the "main" function of the script with that, and it will be
automatically called when ran as a script, but not when imported as a
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list