[Tutor] How to update only set CLI args?

dn PyTutor at DancesWithMice.info
Mon Jan 17 18:32:23 EST 2022


On 18/01/2022 03.23, 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?
> 
> That I can do; I just thought there might be a cleaner way.


+1
@Alan's suggestion plus the more specific need to check *all* input
*before* using it to direct action.


Per your request for a "cleaner way" to merge dicts, Python 3.9+ offers
the dict-union operator (https://docs.python.org/3/whatsnew/3.9.html)

As you have noted, the order in which the dicts are employed is
important, eg

>>> d1 = { "a":1, "c":2, "d": 'Some', }
>>> d2 = { "a":3, "b":4, "d":None }
>>> d1 | d2
{'a': 3, 'c': 2, 'd': None, 'b': 4}

but

>>> d2 | d1
{'a': 1, 'b': 4, 'd': 'Some', 'c': 2}


For your reading pleasure: "Python Merge Dictionaries – Combine
Dictionaries (7 Ways)" (https://datagy.io/python-merge-dictionaries/)
-- 
Regards,
=dn


More information about the Tutor mailing list