[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Jan Kaliszewski zuo at chopin.edu.pl
Tue Nov 26 01:50:25 CET 2013


>> On Nov 25, 2013, at 02:29 PM, Guido van Rossum wrote:
>>
>> >For all I care you can call it ismain().

IMHO the ismain() function is (at least so far) the best option -- 
because:

* it separates the "is it the main module" check from its 
implementation details (__name__ == '__main__') so in a far future (Py 
4.0?) it may become be possible to change those details (e.g. if they do 
not fit well with the import machinery logic);

* beautiful is better than ugly (and -- IMHO -- the current idiom is 
too ugly + inconvenient to type, especially as a common boilerplate...);

* after allowing to pass in an optional stack frame explicitly, it 
could make possible (or at least far easier) to test script 
("run-as-the-main=module") behaviour, e.g.:

     def test_my_module_as_script(self):
         _orig_ismain = builtins.ismain
         def _mocked_ismain(module_frame=None):
             if module_frame is None:
                 module_frame = sys._getframe(1)
             name = module_frame.f_globals['__name__']
             if name == 'my_module':
                 return True
             return _orig_ismain(module_frame)
         with unittest.mock.patch('bultins.ismain', _mocked_ismain):
             sys.modules.pop('my_module')
             import my_module
             <asserts...>

* the feature could be easily backported to older Python versions == as 
a 3rd party module or just not so complex boilerplate code:

     # import_me_anywhere_before_using_the_ismain_function.py:
     import builtins, sys
     def ismain(module_frame=None):
         if module_frame is None:
             module_frame = sys._getframe(1)
         return module_frame.f_globals['__name__'] == '__main__'
     builtins.ismain = ismain

Cheers.
*j



More information about the Python-ideas mailing list