[Tutor] How to update only set CLI args?

dn PyTutor at DancesWithMice.info
Mon Jan 17 18:39:44 EST 2022


On 18/01/2022 12.11, Leam Hall wrote:
> On 1/17/22 08:18, Alan Gauld via Tutor wrote:
>> On 17/01/2022 14: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?
>>
>> Write a loop to test for none values before updating?
>>
> 
> This is what I came up with, after my work day was done.  :)
> 
> ###
> 
> def sort_args(defaults, config, args):
>   """ Returns dict of configuration, with defaults lowest priority,
>       then config file options, then CLI args as highest.
>   """
>   defaults = copy.deepcopy(defaults)
>   defaults.update(config)
>   for key, value in vars(args).items():
>     if value:
>       defaults[key] = value
>   return defaults
> 
> ###
> 
> Back to testing.


If you already know the range of keys (as in this case), they could be
put into a list (which may also be useful in other ways during the
set-up and accumulation of the config vars).

Then the code could loop through the list to build a combined dict.

However, "Danger, Will Robinson": if each config-dict doesn't contain
every key (in said list) - presumably with a value of None.

If that is the case, (I think) a try-except would be 'cheaper' than
sorting... (not that the size/speed is likely to be a real concern)
-- 
Regards,
=dn


More information about the Tutor mailing list