2

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?

1
  • 8
    The idiomatically correct thing is to not care. Really, why limit those functions like that? It is damn handy to be able to call those functions from a new script that wants to reuse those bits. – Martijn Pieters Jul 20 '14 at 0:54
1

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.

1
  • The only thing i can think of that would require this is parsing sys.argv. Pass that in from main if you have to. Otherwise don't waste your time and brainpower preventing people from calling your module's undocumented/private functions. It's their problem if that kind of thing dosen't work right. – StarWeaver Oct 15 '14 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.