This package provides a clean solution for the case where you want to write a Python module that can safely be invoked from the command line but which also needs to be imported by other modules. Simply write each module that would normally make a __name__ == '__main__' check like this instead:

'Your module docstring' import demain __main__ = demain.fix() # Your other import statements # Your classes and functions if __main__: # Your code that gets invoked from the command line

In cases where your module has simply been imported by another module, the fix() function does nothing and returns False . But if your module has been invoked directly, either as a script or using Python's -m option, then fix() will:

Replace your module's __name__ global variable with its true name.

global variable with its true name. Re-register your module in sys.modules under its true name, so that later import statements by other Python modules can find it.

under its true name, so that later statements by other Python modules can find it. If your module is beneath a package, then the module is inserted into the package under its correct name.

After making these corrections, the function returns True so that your module can detect that it is running as the main program.

I advocate that a future version of Python stop mangling module names altogether, and instead set a __main__ boolean in every module like demain does. But until then, use demain to bring your programs some sanity, safely, and fewer mysterious breakages and error messages.