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?
Checking that a function is only run from __main__ in Python
python
What is the idiomatically correct thing to do?As Martijn pointed out, you really shouldn't care about who calls your code.That said, the fact that you do care is a smell that your code isn't broken up logically, but rather wherever you feel like splitting up the code.If your main method is getting too long, look for individual, self contained methods that can be pulled out first. These should be documented well enough that code that imports those scripts can use these methods easily.If you find yourself writing a lot of command line interfaces and it's this code that you don't want being run from another script, consider putting that into a third file and importing and using it from there. That way anyone who feels that there's value in those methods can use them as easily as you would, and it saves you from re-writing the same thing. You may also be able to find an appropriate python lib to do the same thing for you.