I'd like use if __name__ != '__main__':
and then end the execution of a script at that point when it's being imported, rather than doing the usual if __name__ == '__main__':
and indentation of all the rest of the code in the file.
However I have been unable to determine what would cause only this to happen and not have other undesirable side-effects. sys.exit()
stops the whole interpreter and all the other things I've tried either raise some sort of exception or are illegal.
Update:
I've selected @trutheality's answer because it accomplishes what I want and is extremely easy to start using. That said, I thought several of the other answers very interesting and/or clever -- thanks to all who responded -- and plan on investigating some of them further as time permits. I had no idea doing what I want could get so involved.
main.py
foo.py
At top of file
Since python processes a file sequentially, then class Foo would not be defined.
Another thought would be to overload the import logic itself via PEP 302
Best solution IMO: have two files.
module_main.py
actual_module.py
This is "clean" in the sense that an exception is thrown only when something is actually wrong -- no one should ever import
module_main.py
, they should importactual_module.py
.April Fools solution
If you're using python 2.3 there is a
goto
module from entrian, that apparently works! It was made as an April fools joke, and should never be used, (if you look at the source you'll see why: it adds a lot of overhead) but as a proof of concept it seems like the only way I can find to accomplish what you want in any sort of concise way.Another Hack:
So... you've lost the indentation, but also the syntax highlighting and any other features of the editor you were using, unless you comment out the if line every time you edit.
Very similar to my original answer but slightly scarier
partialimport.py
main.py
foo.py
Disclaimer
This is a fantastically terrible hack that will increase the likelihood of your peers murdering you, but this does work.