Last active
December 29, 2023 22:05
-
-
Save vadimkantorov/37518ff88808af840884355c845049ea to your computer and use it in GitHub Desktop.
A one-line example enabling Python's argparse to accept dictionary arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
And this one is the expanded version of it
https://yarimdunya.com/blog/python/argparse/