Python file structure

Ian Kelly ian.g.kelly at gmail.com
Tue May 12 15:54:21 EDT 2015


On Tue, May 12, 2015 at 1:29 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, May 13, 2015 at 5:13 AM,  <zljubisicmob at gmail.com> wrote:
>> If I find an error in command line parameters section I cannot call function usage() because it is not defined yet.
>>
>> I have few options here:
>> 1.      Put definition of usage function before command line parameters parsing section
>
> I'd do this, unless there's a good reason not to. A simple usage
> function probably doesn't have many dependencies, so it can logically
> go high in the code. As a general rule, I like to organize code such
> that things are defined higher up than they're used; it's not strictly
> necessary (if they're used inside functions, the requirement is only
> that they be defined before the function's called), but it helps with
> clarity. That generally means that "def usage():" wants to go up above
> any place where "usage()" occurs, but below the definitions of any
> functions that usage() itself calls, and below the first assignments
> to any global names it uses. It's not always possible, but when it is,
> it tends to produce an easy-to-navigate source file.

+1.

Also, I like to put command-line parsing inside the main function and
make that its *only* responsibility. The main function then calls the
real entry point of my script, which will be something more
specifically named. This also has the advantage that if some other
module needs to invoke my script, all it has to do is call the entry
point function which will be named something more suitable than
"main".



More information about the Python-list mailing list