I often end up with code files that can either be imported or run as __main__
. It's easy to handle this by checking if __name__ == '__main__'
. But sometimes if my main function gets too big I split out pieces of it into other functions, expecting that they'll only be called when __name__ == '__main__'
. Sometimes I enforce this condition by calling the following assert_main
function:
def assert_main():
"Use this in a module you only expect to get run as __main__, not imported"
mod = sys._getframe(1).f_globals["__name__"]
if "__main__" != mod:
raise Exception("Module {} is not main".format(mod))
Other options would include making assert_main
into a decorator or putting the definitions of the functions in question inside of if __name__ == '__main__'
block. And there may well be other options I haven't thought of. What is the idiomatically correct thing to do?