wha wha - 4 months ago 8
Python Question

Is it common to write a lot of code under if __name__ == '__main__': statement

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!

Answer

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.

Comments