This is the Python version of another article, "Getting options in Ruby from both JSON files and command line arguments" (https://qiita.com/aikige/items/014139c0b1ae70139477). With the increasing use of Python these days, I'll share the results of my thoughts on how to write the same thing in Python.
class Optionsopt = Options ('some.json') reads options from a JSON file.opt.option_1.opt.import_opt (options).https://gist.github.com/aikige/470f4ef93753638cc3a18d62e195eb19
#!/usr/bin/env python
import json
import os
class Options:
    OPTS = { 'option_1': 'bool', 'option_2': 'str' }
    def __init__(self, filename='config.json'):
        if (os.path.exists(filename)):
            with open(filename) as f:
                self.import_dict(json.load(f))
    def import_attr(self, key, value):
        if (value is None):
            return
        if (isinstance(value, eval(self.OPTS[key]))):
            setattr(self, key, value)
        else:
            raise ValueError("invalid type")
    def import_dict(self, d):
        for key in self.OPTS.keys():
            if (key in d.keys()):
                self.import_attr(key, d[key])
    def import_opt(self, args):
        for key in self.OPTS.keys():
            if (hasattr(args, key)):
                self.import_attr(key, getattr(args, key))
if __name__ == '__main__':
    import argparse
    opt = Options()
    print(vars(opt))
    parser = argparse.ArgumentParser()
    parser.add_argument('-1', '--option_1', action='store_true', default=None)
    parser.add_argument('-2', '--option_2', type=str)
    args = parser.parse_args()
    print(vars(args))
    opt.import_opt(args)
    print(vars(opt))
bool type, so it's relatively easy to incorporate type determination (import_attr).Recommended Posts