Usage of main()
Scott David Daniels
Scott.Daniels at Acm.Org
Fri Sep 4 11:47:50 EDT 2009
Carl Banks wrote:
> On Sep 3, 11:39 pm, Simon Brunning <si... at brunningonline.net> wrote:
>> 2009/9/4 Manuel Graune <manuel.gra... at koeln.de>:
>>
>>> How come the main()-idiom is not "the standard way" of writing a
>>> python-program (like e.g. in C)?
>> Speaking for myself, it *is* the standard way to structure a script. I
>> find it more readable, since I can put my main function at the very
>> top where it's visible, with the classes and functions it makes use of
>> following in some logical sequence.
>>
>> I suspect that this is the case for many real-world scripts. Perhaps
>> it's mainly in books and demos where the extra stuff is left out so
>> the reader can focus on what the writer is demonstrating?
>
> Speaking for myself, I almost never put any logic at the top level in
> anything other than tiny throwaway scripts. Top level is for
> importing, and defining functions, classes, and constants, and that's
> it.
>
> Even when doing things like preprocessing I'll define a function and
> call it rather than putting the logic at top-level. Sometimes I'll
> throw in an if-test at top level (for the kind of stuff I might choose
> an #if preprocessor statement in C for) but mostly I just put that in
> functions.
If you structure your programs this way, you can get another speedup
for frequently used programs. Create a little program consisting of:
import actual_program
actual_program.main()
Your larger program will only be compiled once, and the dinky one
compiles quickly.
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list