On Sat, Oct 2, 2021 at 1:00 PM Nick Parlante <nick@cs.stanford.edu> wrote:
I have also often wondered if there could be something more turn-key for that bit at the bottom.
Here is a suggestion I'll throw into the ring:
sys.run_main()
It goes at the bottom of the file, and basically just lets the programmer express what they want to happen. Easy to explain. The appropriate logic is buried in run_main(), checking if we're in the __main__ situation, and looking for a main() in the file and running it and probably some corner cases I haven't thought of. I figure sys is the right module, having argv and all that. I would prefer to not have the programmer need to resort to underbar __main()__ type naming to accomplish a thing that is so ordinary. If there were a syntax for this, visualize it showing up in the first day of Python class, at the bottom of hello.py or whatever. You want something easy to explain, not requiring a ton of attention for solving something that is actually quite routine.
I don't mind making the name 'main' special, but you could have an option to specify a different function or make it more agnostic about the name in some other way.
Here's another suggestion. Instead of magical things that are supposed to do what you expect, just write your code and have it do what it does. If you find that you need it to do different things depending on whether it's run as a script or imported as a module, write a condition that tests this. Otherwise, don't. ChrisA