Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no additional indentation with if __name__ == "__main__":

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?

like image 648
mnagel Avatar asked Jan 12 '23 22:01

mnagel


2 Answers

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.

like image 114
Sean Vieira Avatar answered Jan 19 '23 09:01

Sean Vieira


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.

like image 24
Martijn Pieters Avatar answered Jan 19 '23 09:01

Martijn Pieters