[Python-ideas] making a module callable
Steven D'Aprano
steve at pearwood.info
Sat Nov 23 05:14:49 CET 2013
On Fri, Nov 22, 2013 at 10:02:56PM +0100, Philipp A. wrote:
> we’re all accustomed to it, but objectively, it’s horribly implicit and
> unobvious.
Certainly you are correct that it is unobvious, but the "if __name__"
idiom is anything but implicit. It's the opposite, you are *explicitly*
testing whether the module is being run as the main module (__name__ ==
"__main__") and if so, you explicitly run some code.
Of course you can also run code only when *not* the main module:
if __name__ != '__main__':
print "Module is being imported"
else:
print "Module is being executed"
And you aren't limited to a single "main function", you can dot such
tests all throughout your code, including inside functions.
Aside: perhaps it would have been better to have an explicit ismain()
function that returns True when running as the main module, that's more
discoverable.
--
Steven
More information about the Python-ideas
mailing list