bw2 / ConfigArgParse

A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
MIT License
730 stars 121 forks source link

How to import existing ArgParse into ConfigArgParse #165

Open astariul opened 5 years ago

astariul commented 5 years ago

I'm using an external library, which use ArgParse.

I would like to use ConfigParse, in order to give a config file to ArgParse.

Something like :

import lib

parser = lib.get_parser()     # Can't modify the content of this function
# Do something here to add my --config option to the existing parser
args = parser.parse_args()
astariul commented 5 years ago

I end up using a dirty work-around :

import lib
import configargparse

parser = lib.get_parser()

p = configargparse.ArgParser()
parser.__class__ = configargparse.ArgParser
for attribute in dir(p):
   if attribute not in dir(parser):
        setattr(parser, attribute, getattr(p, attribute))
parser.add("--config", is_config_file=True, help="Configuration file path.")

args = parser.parse_args()

As you see, it's dirty but it works.

I'm looking for a cleaner way to achieve this.