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!
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.
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.
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