Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

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]

[0] https://docs.julialang.org/en/v1/manual/performance-tips/ind...



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.


There were some optimisations done in https://bugs.python.org/issue26219


What a great patch history. Love this:

>> Would it be OK if we add this to 3.7beta2?

> 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.


What about Guido's

>PS. I like you a lot but there's no way I'm going to "bare" with you. :-)


Didn't realize this change in 3.8. Curious if anyone has noticed performance improvements upgrading to 3.8.


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.


Would that be different than checking the __name__?

  if __name__ = "__main__":
      mainMethod()


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.

Of course I could just use a real debugger...


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.)


This is true. A related post about discovering this, and some links to more info: https://qht.co/item?id=18681745




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: