What's The Best Practice For Writing An "execute Only" Python Module?
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
Solution 1:
While you indeed can do
if __name__ != '__main__':
raise ImportError(...)
# or maybe just emit a warning
it may stand in your feet the other day.
At least, you should keep the functions, classes and other definitions alone - they don't do any harm and maybe you or someone else needs them later.
If you import a module which just exposes functions and classes and values without doing output or other things, all you lose is some milliseconds.
Instead, you should put the code which executes on startup into a function (main()
?) and execute that in the usual manner.
Post a Comment for "What's The Best Practice For Writing An "execute Only" Python Module?"