Passing of configuration values or arguments into a program

If, for example, a program needed a work directory, there are several ways that the directory could be specified:

  • As a global program constant like WORKDIR = '/tmp/work'
  • On the command line as an argument: this_prog --workdir=/tmp/work
  • As an environment variable: env WORKDIR=/tmp/work this_prog
  • In a configuration file: WORKDIR /tmp/work

If any combination of the above methods were to be used then what should take precedence?

I would suggest commandline argument over environment variable over configuration file over in-program constant. Based on how easy it would be to make a change to the value.

Comments?

Thanks.

I would use the following precedence, highest to lowest:

  • command line argument
  • environment variable
  • user config file, e.g. ~/.myconfig
  • system-wide config file, e.g. /etc/myconfig
  • hard-coded default, e.g. global program constant

If appropriate, e.g. in a GUI program, or an interactive wizard-style program, you can also interactively ask the user for settings; that clearly should be highest precedence of all.

By Steven D’Aprano via Discussions on Python.org at 02May2022 00:23:

I would use the following precedence, highest to lowest:

  • command line argument
  • environment variable
  • user config file, e.g. ~/.myconfig
  • system-wide config file, e.g. /etc/myconfig
  • hard-coded default, e.g. global program constant

The same order for me.

If you want a guideline, think about how hard and/or intrusive a changed
value show be to provide for:

  • command line argument: once off change, not persistent
  • environment variable: local change, persistent for the current session
    (eg terminal window)
  • user config file, e.g. ~/.myconfig: default for “me”, persistent
  • system-wide config file, e.g. /etc/myconfig; default for everyone,
    persistent
  • hard-coded default, e.g. global program constant: default for no
    configuration provided

Cheers,
Cameron Simpson cs@cskk.id.au

Thanks Steven, Cameron. I had missed the site-wide config but would insert it in the order you suggest :blush::+1:t4: