Python file structure

Chris Angelico rosuav at gmail.com
Tue May 12 16:02:42 EDT 2015


On Wed, May 13, 2015 at 5:49 AM, Ned Batchelder <ned at nedbatchelder.com> wrote:
> I would put all of the code into a function some place.  Don't have
> anything at the top level of the file except imports, function (and
> class) definitions, and an "if __name__....." clause at the bottom.
>
> If you need to use globals, assign them inside a parse_arguments
> function that has a "global" statement in it.
>
> This advice is consistent with Chris' "define things before they
> are used."  It does it by defining everything before anything is
> run.

Consistent with, yes, but not for the reason you state. I'm talking
about code layout, not prevention of NameError. For instance, this
would fit your description, and wouldn't error out, but wouldn't fit
my ideal:

import sys

def main():
    if len(sys.argv) < 2: usage()
    # do stuff

def usage():
    print("USAGE: programname arguments")
    sys.exit(0)

if __name__ == '__main__': main()


I would shift the definition of usage() up above main(). Even though
both are executed before main() actually begins running, which
prevents NameError, it's harder to skim the file. Obviously this is an
ideal that can't always be attained (mutual references, for instance),
but where it can be done, it means that the first instance of any
token in a file is its definition - maybe in an import statement (so
"from X import *" violates the principle, but I think most people
avoid it anyway), or maybe in a def/class statement, or maybe a simple
assignment.

ChrisA



More information about the Python-list mailing list