Custom help format for a choice argparse argument

Ivan "Rambius" Ivanov rambiusparkisanius at gmail.com
Fri Jan 27 15:31:22 EST 2023


Hello,

I am developing a script that accepts a time zone as an option. The
time zone can be any from pytz.all_timezones. I have

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-z", "--zone", choices=pytz.all_timezones)
    args = parser.parse_args()
    print(args)
    print(f"Specified timezone: {args.zone}")

It works, but when I run it with the -h option it dumps all entries in
pytz.all_timezones. I would like to modify the help format for just
-z|--zone option. I read the docs about HelpFormatter and argparse.py
and I ended up with

class CustomHelpFormatter(argparse.HelpFormatter):
    def _metavar_formatter(self, action, default_metavar):
        if action.dest == 'zone':
            result = 'zone from pytz.all_timezones'
            def format(tuple_size):
                if isinstance(result, tuple):
                    return result
                else:
                    return (result, ) * tuple_size
            return format
        else:
            return super(CustomHelpFormatter,
self)._metavar_formatter(action, default_metavar)


def main():
    parser = argparse.ArgumentParser(formatter_class=CustomHelpFormatter)
    parser.add_argument("-z", "--zone", choices=pytz.all_timezones)
    args = parser.parse_args()
    print(args)
    print(f"Specified timezone: {args.zone}")

This works, but is there a more elegant way to achieve it?

Regards
rambius

-- 
Tangra Mega Rock: http://www.radiotangra.com


More information about the Python-list mailing list