Friday Finking: Source code organisation

Cameron Simpson cs at cskk.id.au
Sat Dec 28 23:49:27 EST 2019


On 29Dec2019 09:49, Chris Angelico <rosuav at gmail.com> wrote:
>"Define before use" is a broad principle that I try to follow, even
>when the code itself doesn't mandate this. This generally means that
>"if name is main" is the very last thing in the file, and if there's a
>main() function or equivalent, that's usually just before that. Any
>metaprogramming goes right at the top; sometimes this is mandated (if
>I write a decorator function, it has to be above the functions it's
>decorating), but even if it's not, metaprogramming goes before the
>mainline.

For main, i have the opposite habit. If a module has a main() function 
for command line use I usually want that right up the front:

  #!/usr/bin/env python3
  ....
  import...
  
  def main(argv=None):
    ... main command line ...

  classes, functions, etc

  if __name__ == '__main__':
    sys.exit(main(sys.argv))

My reasoning here is that I want the main programme obvious up front.

But then I loosely follow "define before use" after that.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list