Do you recommend using top level code or if __name__ == '__main__'? Why?

Wondering if there is a reason to prefer this:

if __name__ == '__main__': 
  sys.exit(main())

over just starting from line one and executing code. If starting from line one, should you mix other functions into your main script?

Why do you prefer it?

The if __name__ == "__main__" idiom is needed only when (a) your script needs to run directly, AND (b) your script needs to be imported as a module. Otherwise, just put top-level code.

3 Likes

One might as well use the if __name__ == "__main__" idiom most of the time, as it doesn’t get in the way and you may want to use the code as a module later.

The only time it may get in the way for me is when I am writing for execution in an ipython/jupyter cell-based interactive environment.

1 Like

I often use if __name__ == "__main__" even if not yet ready for direct
execution, because then i put the top level code in a main() function
which:

  • is up the top where I can see it
  • leaves no global variables littering the namespace

So:

 imports...

 def main(argv=None):
     if argv is None:
         argv = sys.argv
     ...

 ... functions, classes etc

 if __name__ == "__main__":
     sys.exit(main(sys.argv))

Saves me time later.

Cheers,
Cameron Simpson cs@cskk.id.au

I’m curious about the sys.exit part. Why not just call main() by itself? What’s the reason for passing it into sys.exit?

That means that your main function can return 0 to indicate success, or return 1 (or any other nonzero number) to indicate failure.

Ah, just like C. What happens if you don’t call sys.exit? Will it always return 0 in that case?

Correct. Also, a post has to be more than ten characters, so here is some padding.

Gnarly details: sys — System-specific parameters and functions — Python 3.11.0 documentation

I only ever use it to return 0 (success), 1 (most failures), 2 (bad
invocation/usage) and occasionally other small nonzero ints if the
programme has a suite of defined failure modes.

Returning None (eg main() forgets an explicit return) is also like
returning 0.

Cheers,
Cameron Simpson cs@cskk.id.au