[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Andrew Barnert abarnert at yahoo.com
Mon Nov 25 18:14:31 CET 2013


On Nov 25, 2013, at 6:12, Steven D'Aprano <steve at pearwood.info> wrote:

> To understand the current "if __name__" idiom, the user only needs to 
> understand the if statement and the rule that Python defines a special
> global variable __name__. To understand this run_if_main idiom, the user 
> has to understand decorators. It's hard to believe, but I've come across 
> people -- even quite experienced Python developers -- who avoid 
> decorators because they don't quite get how they work. And of course 
> beginners have no idea what a decorator is. These means explaining about 
> higher-order functions.

No, it really doesn't. In order to write a decorator, or read it's code, you have to understand HOFs. But to use a decorator? I've seen many people successfully using @property, @classmethod, etc. without even knowing that they're functions. (Never mind that most of them have no need for those decorators, the point is that they have no problem figuring out how to use them.)

I don't like the decorator idea either, but I think this is the wrong argument.

Guido's points that it's too magical, and ends up providing less power with that magic than you already have without, seem better.

But Steven's bikesheddability argument (right next to the "have to understand decorators" argument) is what really sells me that this is the wrong answer. All those options means that people will have to learn or look up which option Python chose--and, as usual, many novices won't even realize there was an option to choose from, assume wrong, and have to ask someone "Why does my code after the @is_main function never get run, while the same code after an old-style if __name__ block does?" because they don't realize that the main function's result is passed to exit because they never even realized such a thing was possible.


More information about the Python-ideas mailing list