Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse yaml directories as key=value pairs #273

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

katharinahafner
Copy link

Fix #258

@katharinahafner
Copy link
Author

Minimal example:

# config.yml
vars:
  a: [1, 2, 3]
  b: "foo"
  c: "bar"

Add an action to parse dict-string to dict

import argparse
from configargparse import ArgParser, YAMLConfigFileParser

class StoreDict(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        import json
        try:
            my_dict = json.loads(values)
        except json.JSONDecodeError:
            my_dict = json.loads(values.replace("'",'"'))
        setattr(namespace, self.dest, my_dict)

p = ArgParser(config_file_parser_class=YAMLConfigFileParser)
p.add('-c', '--config_file', default='config.yml', is_config_file=True)
p.add('--vars', dest="vars", action=StoreDict)
args = p.parse_args()

print(args.vars)
Output: {'a': [1, 2, 3], 'b': 'foo', 'c': 'bar'}

@bw2
Copy link
Owner

bw2 commented Jun 27, 2023

If other users would like to see support for dictionaries, please post your views here or in #258

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Parse yaml directories as key=value pairs
2 participants