3

my current coding style is like

import xxx

def fun1()
def fun2()
...

if __name__ == '__main__': 

    task = sys.argv[1]
    if task =='task1':
        do task1
    elif task == 'task2':
        do task2
    ...

my problem is that the part of the code under

if __name__ == '__main__': 

is quite huge comparing to the functions defined above and I was told this is not a good programming style. It is due to the fact that I modify stuff and do experiment in each tasks frequently and I want to separate those part of the code away from functions which are less likely to be modified. I want to learn more advice here, thanks!

Wang
  • 869
  • 9
  • 26
  • 4
    It's better to wrap it all up into a single `main()` function, then call this function under your `if __name__ == '__main__'` – AdrienW Aug 04 '16 at 09:41
  • I agree with BusyAnt, define a main() and do it there because if `__name__ == __main__` only gets called if this is the main routine, so on import it won't ... – AnyOneElse Aug 04 '16 at 09:43

2 Answers2

4

Like BusyAnt said, the common way to do it is

import xxx

def fun1()
def fun2()
...



def main():
    task = sys.argv[1]
    if task =='task1':
        do task1
    elif task == 'task2':
        do task2
    ...

if __name__ == '__main__':
    main()

The upside of this is it does not run on import, but main() can still be run from another module or file if so preferred.

Pax Vobiscum
  • 2,385
  • 2
  • 20
  • 31
  • 1
    Thanks for quoting @Uzzee, I was actually writing an answer from it myself. :) – AdrienW Aug 04 '16 at 09:46
  • 2
    Say this file is named `script1.py` and if we import it to another file called `script2.py`, the ``__name__`` variable will not equal to `'__main__'` but to `'script1'`, and therefore `main()` will not be run by default. We can however choose to run it by typing `script1.main()` in our script2.py file. – Pax Vobiscum Aug 04 '16 at 09:53
3

It is not forbidden to write a lot of things under if __name__ == '__main__', though it is considered better and more readable to wrap everything up in a main() function. This way, the code in main() isn't executed when you import this module in another module, but you can still choose to run it, by calling imported_script.main().

Your code would then look like this :

import xxx

def fun1()
def fun2()
...


def main():
    task = sys.argv[1]
    if task =='task1':
        do task1
    elif task == 'task2':
        do task2
    ...

if __name__ == '__main__':
    main()

I encourage you to read about what does this if statement do, among the many questions asked about it.

Graham
  • 7,035
  • 17
  • 57
  • 82
AdrienW
  • 2,441
  • 4
  • 22
  • 51