One benefit of using a main function in Python is performance. If you’re doing significant computation at the top-level, it’ll probably run faster if moved into a function.
I believe this comes from the fact that local-variable lookup is faster than global-variable lookup - because the former is lookup-by-index and the latter is lookup-by-name.
The same is true in Julia: “Any code that is performance critical or being benchmarked should be inside a function.” [0]
Not just because it's a lookup-by-name, but because globals are mutable everywhere, the interpreter has to assume that some other code has mutated the variable and has to re-fetch it in many cases.
> It's up to the release manager, but personally it feels like you're pushing too hard. Since you've done that frequently in the past I think we should help you by declining your request. 3.8 is right around the corner (on a Python release timescale) and this will give people a nice incentive to upgrade. Subsequent betas exist to stabilize the release, not to put in more new stuff.
Another benefit is re-usability. If you want your program to be callable as module or script from elsewhere without going through the tedious shell functions, "def main()" is the only way to go.
The difference is that you've encapsulated your coding logic in mainMethod() instead of writing under that if condition itself. If latter was the case, you can't call that code from another module without resorting to os shell level features.
The code encapsulated into "__main__" assumed to be module-specific, this is the purpose of that pattern. If you want to make some code available for another module, you just refactor it into separate function.
But the downside is that I like to use ipython and %run the file and if it's not in a function, I can then inspect all the intermediate variables and not just the result. Every time I do put it in a function, I regret it for this reason.
The same is true in Julia but for slightly different reasons. It's not just quicker variable lookup in Julia, but the fact that it will be JIT compiled. (Unlike CPython.)
I believe this comes from the fact that local-variable lookup is faster than global-variable lookup - because the former is lookup-by-index and the latter is lookup-by-name.
The same is true in Julia: “Any code that is performance critical or being benchmarked should be inside a function.” [0]
[0] https://docs.julialang.org/en/v1/manual/performance-tips/ind...