i know that it is good style to define a main() method for "script-style" python programs so it can optionally be included as a module later on.
so let's assume this code (random snippet):
a = 5
if a > 0:
print a
becomes
def main():
a = 5
if a > 0:
print a
if __name__ == "__main__":
main()
causing all my code to be indented one more level. i try to avoid unnecessary indentation/nesting in my code for maximum clarity, and thus i am wondering if something can be done here, like e.g.
if __name__ != "__main__":
return # just leave this file
a = 5
if a > 0:
print a
but (of course) this triggers:
SyntaxError: 'return' outside function
is something like this possible? advisable? idiomatic?
You can do this:
if __name__ != "__main__":
throw TypeError("Attempted to import command-line only script")
# Your code here
However, I would advise against this pattern - most of the time it should be pretty obvious that a script is command-line only. And if someone has a use case for something that you defined in a script they shouldn't have to edit it just to be able to import one function.
Nope, not possible, really.
When __name__
is not '__main__'
your module was imported by another piece of code, as a regular module. You cannot bail out early in that case.
And what's wrong with a one time extra indentation level? Just hit tab in the editor, and be done with it? Personally, I find that using a main()
function documents the intent much better than leaving the code unindented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With