What to do when the __name__ shouldn't equal '__main__'

时间:2015-07-28 16:18:06

标签: python python-2.7 python-3.x

I see a lot of people doing

if __name__ == '__main__':
    main()

where main() presumably has all the useful code. What if I don't want the script to be imported? It doesn't have useful functions/classes to import. Is it just as elegant to do

if __name__ != '__main__':
    sys.exit()
    print('this script shouldn\'t be imported')

when your code won't do anything for the outsider?

2 个答案:

答案 0 :(得分:3)

Unless the code simply won't run correctly when it is imported, I would strongly recommend against adding unnecessary safeguards. Don't treat others like children - let them decide. All you need to do is provide documentation about the correct usage.

In the case that someone should import module A instead of B because of some weird order of execution issue, you could raise an exception with a message directing the user to A. But this really isn't a common scenario.

答案 1 :(得分:3)

Don't worry when your code is being imported, but worry if nobody wants to import it! :)

Indeed What for to protect it in such a way? If one person has you script it can easily fix it and allow importing. Best way is to let people decide how to import the code: use as a module or a script.