I have a Python module that is intended exclusively for running as a script and never as something that should be imported, and I'd like to enforce (and communicate) that intention in my code.
What is the best practice for accomplishing this?
I can imagine a few options such as wrapping the whole file in
if __name__ == '__main__':
# All the code in the module
or aborting at the start
if __name__ != '__main__':
exit()
# All the code in the module
perhaps with a warning
if __name__ != '__main__':
print('You should not import this')
exit()
# All the code in the module
or even an assertion
assert __name__ == '__main__', 'You should not import this'
But I'm not sure which (if any) is appropriate, stylistically or technically.
Copyright Notice:Content Author:「orome」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/20923892/whats-the-best-practice-for-writing-an-execute-only-python-module