[Tutor] How to update only set CLI args?

Leam Hall leamhall at gmail.com
Mon Jan 17 18:11:46 EST 2022


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.

Leam

-- 
Site Automation Programmer (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)


More information about the Tutor mailing list