cbolwerk
cbolwerk

Reputation: 430

Update argparse namespace with other namespace/dictionary

Let's say I have two argparse namespaces

parser1 = argparse.ArgumentParser()
parser1.add_argument('--name', type=str, required=False, default='John')

args1 = parser1.parse_args()

parser2 = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
parser2.add_argument('--name', type=str, required=False)

args2 = parser2.parse_args()

How can I update args1 with args2? I am aware of updating dicts, i.e.

dict = {'name': 'Pete'}
dict.update(**vars(args2))

This should work I think (not tested), but can you also update an argparse namespace with another namespace? I would be fine with converting args2 to a dict to be able to update.

Upvotes: 1

Views: 2018

Answers (1)

hpaulj
hpaulj

Reputation: 231395

In the subparser Action class, argparse.py uses:

    subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
    for key, value in vars(subnamespace).items():
        setattr(namespace, key, value)

to copy update namespace with values from subnamespace. argparse uses the generic setattr to set values, minimizing assumptions about valid names.

You might also be able to use

 namespace.__dict__.update(subnamespace.__dict__)

but I haven't tested it.

Upvotes: 2

Related Questions