On 11/12/20, Chris Angelico email@example.com wrote:
I actually don't use the "if name is main" idiom all that often. The need to have a script be both a module and an executable is less important than you might think. In a huge number of cases, it's actually better to separate out the library-like and script-like portions into separate files, or some other reorganization.
One caveat is that the module __name__ check is required for multiprocessing in spawn mode (as opposed to fork mode), which is the only supported mode in Windows.
Generally, I think scripts in installed packages are better handled via setuptools entrypoints nowadays. For cross-platform support, pip automatically does the right thing for Windows by creating executable .exe launchers. The issue is two-fold: the default action of the .py file association is often configured to edit rather than execute scripts, and, irrespective of the latter, many execution paths, such as subprocess.Popen, use CreateProcess from the base API, which does not support file associations. (File associations are the closest Windows has to Unix shebangs, and the basis for how the py.exe launcher supports Unix shebangs in scripts, but they're implemented in the high-level shell API instead of the base API.)