2007-03-21

A possible change to handle "main" code in a module

I think every Python programmer learns early on the ``if __name__ == '__main__'`` idiom. It's fairly simple and it makes sense when you explain what is happening. Plus it nicely ties into the fact that Python modules are actually executed when imported.

The problem is that they partially break down when using the new relative imports (e.g., ``from .. import foo``). The problem is that to calculate the absolute name of the foo module being imported, import takes the caller's __name__ value from its global namespace, splits on '.', and then subtracts off parts on have many levels up the import needs to go to search for the module.

But when the module with a relative import has it's name set as '__main__', the name resolution for relative imports doesn't work (you end up with an ImportError). This sucks when you want to use a file in a package as an executable script for something. How can this be solved?

The idea I came up with while this was discussed on python-ideas (don't remember how long ago; possibly two months?) was to make __main__ a built-in variable that stored the name of the module currently being executed. This would allow the idiom to be changed to ``if __name__ == __main__``. This has a perk of no longer having to set the '__main__' key in sys.modules any longer. It also prevents errors by mistyping the string '__main__' and instead relying on a variable name.

Obviously another option is to go with defining a special function name that automatically gets executed when the module is first imported. I personally, though, don't like that solution as much.

Anyway, if feedback on this post is positive I will propose this back on python-ideas and then hopefully to python-3000 after that.