Skip to content

Instantly share code, notes, and snippets.

@non7top
Forked from vadimkantorov/argparse_dict_argument.py
Created December 29, 2023 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save non7top/a094634d0c382636bc817a0b7a12258a to your computer and use it in GitHub Desktop.
Save non7top/a094634d0c382636bc817a0b7a12258a 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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment