0

If I've got a script that uses a config file (or defaults to a generic config file) that calls another module which needs the config file passed to it as a parameter should I always

File 1 (the script): /bin/runner

include doer.py

... initializing backup conf file
   backup_conf_file = "/etc/thing.conf"

... processing opts and args ...
   if ("backup_conf_file" in opts):
      backup_conf_file = arg



doer.copy_thing(backup_conf_file)

File 2 (the module): /lib/doer.py:

def copy_thing(backup_conf_file="/etc/thing.conf"):
   """Do stuff"""

So, I obviously did something wrong above, but what is the right way to do it? I'd like to allow testing the script with a different conf file location and I'd like to allow testing the module with a different conf file location.

What I'd really love would be a feature where I can call copy_thing with backup_conf_file=backup_conf_file or DEFAULT if None), but unless that exists and I don't know about it, what should I be doing here?

Peter Turner
  • 6,897
  • 1
  • 33
  • 57

1 Answers1

1

/lib/doer.py shouldn't know about the default at all. Remove the default parameter and have /bin/runner pass in the correct config file to use.

If opts is a dictionary, use code like this:

backup_conf_file = opts.get("backup_conf_file", "/etc/thing.conf")

That will give you either the value in the dictionary or /etc/thing.conf.

If these are command line arguments, you should use argparse or similiar which will let you set the default for a config file parameter.

Winston Ewert
  • 24,732
  • 12
  • 72
  • 103
  • I use getopt for getting the parameters from the commandline, but I wasn't trying to ask about that. What I want to know is why is it better to put the default there? I don't want to have to type it all the time when I'm testing :) (maybe it's a giveaway that I'm converting a perl script to python and I desire laziness) – Peter Turner Dec 19 '17 at 18:28
  • @PeterTurner, why do you have to type it in all the time while testing? If it is defaulted in the runner, isn't that enough? – Winston Ewert Dec 19 '17 at 20:52
  • sometimes I like to import the module into the python shell and run it there. – Peter Turner Dec 19 '17 at 20:59
  • 2
    hmm... don't do that. But if you insist, have the parameter to `copy_thing` default to `None`, then have a line: `if backup_config_file is None: backup_config_file = '/etc/thing.conf'`. Then runner can pass either the filename or None, and you'll specify the default in only one place. – Winston Ewert Dec 19 '17 at 22:15