0

I run a python program with a long argument list (> 20 arguments). Arguments have all a default values (if not overriden by user). At the program's startup, I print the effective argument to have a trace of how the program has been started. Today I print using a dumb routine:

def print_config(args):
    print("Configuration:")
    print("  shoes:   {}".format(args.shoes))
    print("  socket:  {}".format(args.socket))
    [...]

How can I print this using a smart iterator?

m-ric
  • 5,621
  • 7
  • 38
  • 51
  • 1
    See http://stackoverflow.com/q/16878315/3901060 for a way to make a dictionary out of `argparse`'s `Namespace` object. Then you can iterate over it. – FamousJameous Mar 29 '17 at 22:36

1 Answers1

1

args is a argparse.Namespace object. That class, or rather its super has a repr method. That's what you see when you do

print(args)

The relevant lines of the repr (which you can find in the argparse.py file) are:

    arg_strings = []
    for name, value in sorted(self.__dict__.items()):
        arg_strings.append('%s=%r' % (name, value))
    return '%s(%s)' % (type_name, ', '.join(arg_strings))

If you joined with '\n' instead of ', ', it would give something close to your version.

vars(args) gives the same dictionary as args.__dict__.items().

print(parser.parse_args([])) will show all the defaults, without any user input. Of course that won't work if there are required inputs.

hpaulj
  • 221,503
  • 14
  • 230
  • 353