Best IMO solution: there are two files.
module_main.py
import actual_module.py if __name__ != '__main__': raise RunTimeError("You should be importing actual_module.py, not module_main.py")
actual_module.py
# Actual module code (classes, functions, etc)
This is "pure" in the sense that an exception is thrown only when something is really wrong - no one should import module_main.py , they should import actual_module.py .
April Fools Solution
If you are using python 2.3, there is a goto module from entrian that seems to work! It was made as a joke in April, and should never be used (if you look at the source, you will understand why: this adds a lot of overhead), but, as a proof of concept, it seems like the only way I can find to perform what you want in some kind of compressed form.
from goto import goto, label # Code that should always be imported (classes etc.) if __name__ != "__main__": goto .end # Stuff to be executed when this is main, NOT indented label .end
source share