Chris Angelico wrote:
On Fri, May 29, 2020 at 5:25 AM Alex Hall alex.mojaki@gmail.com wrote:
On Thu, May 28, 2020 at 12:57 PM Paul Sokolovsky pmiscml@gmail.com wrote:
And in all fairness, all good ideas already came to somebody else years ago. There's https://www.python.org/dev/peps/pep-0299/ , successfully rejected yet back in 2002. (So, feel free to use it in your own environment/Python dialect.) Thanks for the link. Pity it was rejected. I can think of one reason I'd quite like this beyond it being DRY and concise: I often see code written by others like this: def foo(bar): print(bar)
if __name__ == '__main__': bar = 3 foo(bar)
Now bar is both a local and global variable, which leads to both annoying IDE warnings and actual bugs. I think I encountered a bug related to this when someone used eval() (which was the right thing to do in this case) and didn't specify the namespaces correctly, but name shadowing made it seem like their code was correct. Point is, I'd like something that encourages people to put all their __main__ logic and variables into a function, rather than a module level conditional. People can already put all their main logic into a function. If you
want to unit-test your main function, that's the best way to do it. The trouble is, how much goes into main() and how much into if __name__ == '__main__'? For example: Does your main function accept a list of arguments, or does it look in sys.argv? Neither answer is wrong. And that means the best way is to NOT force everyone across all of Python to choose the same way - let people write their code their way. ChrisA
It is not enforcing user it just to provide more choice: ```python if __name__ == '__main__': ... main logic ... ``` or this way: ```python def __main__(); sys.argv[0] ... main logic ... ``` `__main__` will be called only once at the end of script if it was called as script Also on additional benefit, it will help people that came from other languages: ```rust fn main() { ... } ``` or ```c void main() { ... } ``` or ```java class MyClass { public void main(...) { ... } } ``` and in Python it could look like this: ```python def __main__(); ... main logic ... ```