On Fri, Oct 01, 2021 at 11:59:33PM -0400, Jonathan Crall wrote:
It's true that it's just a two-line pattern, and not all simplifications of two line patterns make it into the python standard. But this is an extremely common two line pattern. One that's often written less efficiently than it could be. If you already wrote the if statement for name, a new programmer is not incentivized to write a separate main function and then call it, it would be simpler if there was some construct that just declared this is the main function, and then the code inside the function is executed.
For giant single file scripts, that are just protected by an if name equals main, this could be a big performance improvement. Although I imagine in the average case it won't impact that much. But there may be some small benefit. The biggest benefit will be in the clarity of the code, the state will be easier to reason about because there will be less globals.
*This*. For me, the clarity of code is the most important aspect. Instead of open-coding a very common runtime check, we *declare* that some function is the entry point. People have argued elsewhere in the thread that writing 'if __name__ == …' is easy. It is, but it also gets in the way: 1. we don't have a function scope. When the "main block" is a few lines, this doesn't matter so much. But quite often it starts as a line or two, but then you add option parsing, and maybe some prints, and then have non-trivial code executed in the top-level scope, with variables that are *meant* as local visible in the module global scope. (In my experience it's a fairly common bug where we want to pass all state to functions through parameters, but forget a variable. The function still works because it gets the variable from the global scope, but when it's called from a different module, without going through the "main block", the variable is not defined.) 2. If we want to call the "main block" from a different module, either for testing or for any other reason, we can't without jumping through hoops. 3. I know some people argue that 'if __name__ == …' is very pythonic and just great, but in my experience with teaching python, it is confusing and unclear. The problem is that it is pretty much the only place where this kind of conditional would be used. Unless you're doing some advanced stuff, there is simply no other reason to ever check the name of the current module. So explaining 'if __name__ == …' requires explaining what __name__ is, and that it is set one way normally, but to '__main__' in other situations. Overall, 'if __name__ == …' seems like a cute pattern, but it doesn't "scale" properly. Zbyszek