Question regarding style/design..

Robert Kern robert.kern at gmail.com
Fri Jul 17 13:45:44 EDT 2009


On 2009-07-17 12:11, Tim Chase wrote:
>> Sometimes I see relatively small application, generally task scripts,
>> written as essentially a list of statements. Other times, I see them
>> neatly
>> divided into functions and then the "if __name__ == '__main__':"
>> convention.
>> Is there a preference? Is there an... application scope such that the
>> preference shifts from the former to the latter? I understand the use
>> of the
>> __name__ == 'main' convention for building unit tests, but I'm mixed on
>> using it in scripts/small applications.
>
> This may circle around to the "is Python a scripting language" bruhaha a
> while back. I tend to skip the __name__ == '__main__' in what I'd
> consider scripts (one-file hacks to solve an immediate problem, often
> disposable or one-use wonders). However for non-scripts (which I'd
> define as code that has more than one source-code file I've written or
> that I'd have to maintain) and for modules, I tend to put in the
> __name__ guard.

I definitely suggest always using the __name__ guard no matter what. Habits are 
important, and it's usually more of a waste of time trying to determine if you 
are writing a "script" or a "program" than it is to just write the clause all 
the time. One of the ex-DivMod guys (Glyph?) has a good blog post on the subject 
of writing docstrings and the Suzuki Method of violin; however, I cannot find 
it. With a good programmer's editor that can do macros or "snippets", this 
particular habit can be basically cost-free.

There are also technical limitations to be aware of. Even if you don't think you 
will ever import the script, other tools might. For example, on Windows, 
multiprocessing needs to import the main module of the parent process in order 
to do some of its operations. If you do not have a __name__ guard, you will go 
into an infinite regress as your subprocesses execute the main code and create 
subsubprocesses until you finally manage to kill them all. Extra fun if it is a 
GUI and you have to click all of the windows closed.

Don't waste half a day trying to figure out why your script mysteriously doesn't 
work. Learn from my mistakes. :-)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list