OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

about main()


On 05/07/2018 11:22, Rhodri James wrote:
> On 05/07/18 09:43, Abdur-Rahmaan Janhangeer wrote:
>> just when to use main() in
>>
>> if __name__ == '__main__' :
>> ???? main()
>>
>> is far is it good in py?
>>
>> or should file intended to be run just not include it?
> 
> It's a matter of taste.? If your "file intended to be run" also contains 
> things that might be useful as a module, use the "if __name__ == 
> '__main__'" trick.? Otherwise it can be more of a distraction than a 
> help.? I'm not a big fan of "main()" functions myself; creating a 
> function which will be called exactly once seems rather wasteful.

Wasteful of what? Since it will only be called once, that is not exactly 
an overhead.

But packaging the main function like that has some advantages:

1. It /is/ tidily packaged

2. You can place it anywhere in the program

3. It can be more easily copied

4. If you had a need to, it could call itself

5. If sometimes you had to wrap extra code around it, that becomes easier:

     prologue()
     main()
     epilogue()

6. If you had to run it more than once /within the same execution 
environment/, that is easier too.

7. If you had a choice of main1() and main2(), that becomes easier as well.

Actually, I can't think of any downsides.

Not packaging main() into its own function reminds of sprawling, 
unstructured Fortran code from the 1970s, when people even frowned upon 
putting long stretches of code into a subroutine.

-- 
bart