'Is it possible to invert the python __main__ test - ie stop parsing

I'm dealing with a bunch of old (ie legacy - ie don't break them) python scripts in a directory, adding unittests and modularising them (ie adding __init__.py).

For the large number of "just scripts" they need to be changed to have the __main__ guard so that they are not run when unittest runs discovery (or module import).

I can break them up

## imports and defs

## functions

if __name__ == '__main__':

   ## rest of script goes here

However this puts a big dent in the git history as everything needs to be reindented.

My preference would be to invert the test


if __name__ != '__main__':
   STOP_RUNNING_HERE

## rest of script goes here

The obvious thoughts for STOP_RUNNING_HERE are return (not valid) and exit() (I don't want to exit someone loading the code).

Is there any way the guard can be inverted like this?

PS: I know I could just reformat, or move the "script/main" code out of this directory - I'm trying to avoid major changes - or keep all changes simply reviewable - as I said this is legacy code that has unknown usage in arcane build scripts - we don't have time to re-write everything correctly in one big go - I just want to improve where I can and leave alone as much as possible.

I'm convinced there probably isn't an answer, but couldn't find anyone answering the question specifically out on the internet.



Solution 1:[1]

No, there is no other way to invert the test besides using your original idea of indenting the rest of the script after the if __name__ == '__main__'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ethan Furman