Total newbie question: Best practice

Arnaud Delobelle arnodel at gmail.com
Tue Nov 29 15:34:01 EST 2011


On 29 November 2011 20:06, Colin Higwell <colinh at somewhere.invalid> wrote:
> Hi,

Hi Colin, and welcome to Python :)

> I am just starting to learn Python (I have been at it only a few hours),
> so please bear with me. I have a few very small scripts (do you call them
> scripts or programs?) which work properly, and produce the results
> intended.

I think you can call them either.

> However, they are monolithic in nature; i.e. they begin at the beginning
> and finish at the end. Having done a little reading, I note that it seems
> to be quite common to have a function main() at the start (which in turn
> calls other functions as appropriate), and then to call main() to do the
> work.
>
> Is that standard best practice?

When code should be put in a function is a matter of judgement in the
end, so it's not an easy question.  But roughly speaking:

- if you need to perform the same task at several points in you
program, then it's a good idea to put this in a function.  It avoids
duplication of code, minimises the chances for bugs, makes the program
easier to read (provided you find a nice name for the function!) and
also improves testability.

- if there is a task that could be performed is several different ways
but with the same result, then it's good to put in a function.  This
way when reading the program you can focus on the important thing,
which is the result of the process, without being distracted by the
details of how the result is arrived at.  Moreover, it gives you added
flexibility as you can later try a different method for performing the
same task and very easily plug it into your existing program to see if
it improves performance for example.

- if you have a piece of code which is too long to be understood
easily, consider whether you could break it down into smaller bits,
each of which has some meaning of its own, and make each bit into a
function with a name that describes clearly what it does.  Then
rewrite your big piece of code in terms of these functions.  It will
make your program a lot easier to understand when you come back to it
in the future.

As for the main() function, I don't think it is standard practice in
Python.  There is no requirement to have a main() function.  You can
use the idiom:

if __name__ == "__main__":
    ...

which will execute if you call the file as a script (as opposed to
importing it as a module)

-- 
Arnaud



More information about the Python-list mailing list