[Tutor] How to update only set CLI args?

Peter Otten __peter__ at web.de
Mon Jan 17 10:00:06 EST 2022


On 17/01/2022 15:00, Leam Hall wrote:
> Writing a CLI app in Python 3.10. There's a "defaults" dict, a config 
> file that gets read into a dict, and command line arguments that can be 
> passed in.
> 
>    defaults = {'table':'people'}
>    defaults.update(config)
>    defaults.update(vars(args))
> 
> The issue is that if an argument is not set on the command line, the 
> args.item has a value of "None", which then overwrites any value in 
> defaults or config. How do I update just the set args?

Do you process command line arguments with argparse?
Then you might pass a custom namespace filled with your defaults:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--table")
parser.add_argument("--extra")

defaults = dict(table="people")
ns = argparse.Namespace()
vars(ns).update(defaults)

print(parser.parse_args(namespace=ns))




More information about the Tutor mailing list