5

Suppose you are developing a Python standalone application (not a library).

  1. Would you make it a Python package? Or just files next to each other?
  2. If you would make it a package, what would be the "starting point" file (where the first line of code runs)? The __init__.py? Or a short "startup" script outside the package which calls a function in the package?
gnat
  • 21,442
  • 29
  • 112
  • 288
Aviv Cohn
  • 21,190
  • 31
  • 118
  • 178

1 Answers1

5

If the whole application fits into a single file, that is the most simple solution.

Otherwise, it is best to create a complete package. When you create a setuptools-based setup.py file, you can define various entry points that should be installed as scripts. However, these entry points refer to functions, not files.

Instead of running a script with Python (python path/to/script.py args...), you can also run a module or package: python -m example.package args.... For modules (i.e. Python files), you have to do the if __name__ == '__main__' check and dispatch to your main function. For packages (i.e. directories with an __init__.py file), you have to create a __main__.py file as an entry point. It makes sense to put the argument parsing & user interface code here.

This is particularly sensible when adding a command line interface to an existing library. However, it is often elegant to write the central behaviour of an application as a library, and then only wrap that library with a simple user interface. In particular, this layered architecture makes unit testing easier.

amon
  • 132,749
  • 27
  • 279
  • 375
  • So to summarize, for a standalone app you suggest making it a package, and putting the 'main' function - the code which is supposed to run first - in the `__main__.py` file? – Aviv Cohn Oct 24 '16 at 01:45
  • @AvivCohn Yes, that's probably the best solution when the app consists of multiple files. – amon Oct 24 '16 at 05:19