سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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.

A function should do one thing and this also applies to main. It should do (some) main stuff and everything else should be done in functions and classes.

There is absolutely no reason to see this as an "unnecessary indentation"…

You'd have to induce the importer itself to behave differently. It might be possible, though difficult, but certainly not advisable, as you'd be introducing some very unexpected behavior.

If you really want to avoid the extra indentation, you could, I suppose, implement a 'public' and 'private' module, where the public module branches based on if __name__ == '__main__' to load a different private module. But that seems like a lot of hoops to jump through to avoid a few extra indentations. In any case, if your main() is long enough that the indentation is bugging you, you should probably think about breaking more of it out in to functions in the first place.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top