Skip to content

Instantly share code, notes, and snippets.

@vadimkantorov
Last active December 29, 2023 22:05
Show Gist options
  • Save vadimkantorov/37518ff88808af840884355c845049ea to your computer and use it in GitHub Desktop.
Save vadimkantorov/37518ff88808af840884355c845049ea to your computer and use it in GitHub Desktop.
A one-line example enabling Python's argparse to accept dictionary arguments
# Example:
# $ python argparse_dict_argument.py --env a=b --env aa=bb
# Namespace(env={'a': 'b', 'aa': 'bb'})
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--env', action = type('', (argparse.Action, ), dict(__call__ = lambda a, p, n, v, o: getattr(n, a.dest).update(dict([v.split('=')])))), default = {}) # anonymously subclassing argparse.Action
print(parser.parse_args())
@Byun-jinyoung
Copy link

Byun-jinyoung commented Dec 14, 2020

Good! It is very benefical. Thank you!

@gluttony38
Copy link

Awesome, all I found to do this was using giving a "hard to build" argument like, for your example "{'a': 'b', 'aa': 'bb'}" then parse it with json, and even if we need to give several --env in your case, it is very much non-developer user friendly.
Thanks !

@ozcanyarimdunya
Copy link

ozcanyarimdunya commented Feb 10, 2022

And this one is the expanded version of it

import argparse


class ParseKVAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, dict())
        for each in values:
            try:
                key, value = each.split("=")
                getattr(namespace, self.dest)[key] = value
            except ValueError as ex:
                message = "\nTraceback: {}".format(ex)
                message += "\nError on '{}' || It should be 'key=value'".format(each)
                raise argparse.ArgumentError(self, str(message))


parser = argparse.ArgumentParser()
parser.add_argument(
    "-H",
    "--host-names",
    dest="hosts",
    nargs='+',
    action=ParseKVAction,
    help='Parameter accepts -H host1=localhost "host2=other hosts"',
    metavar="KEY1=VALUE1",
)

https://yarimdunya.com/blog/python/argparse/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment