1

Is it possible to simplify this:

def method(self, **kwargs):
    if kwargs.get('profile_id') is None:
        kwargs['profile_id'] = 'something1'
    if kwargs.get('status') is None:
        kwargs['status'] = 'something2'
    if kwargs.get('account_type') is None:
        kwargs['account_type'] = 'something3'
    if kwargs.get('external_account_id') is None:
        kwargs['external_account_id'] = 'something4'
    if kwargs.get('vendor') is None:
        kwargs['vendor'] = 'something5'
    if kwargs.get('created_timestamp') is None:
        kwargs['created_timestamp'] = 'something6'

    return ClassOne.objects.create(**kwargs)

This works, but I'm just curious if there is something more elegant. I was thinking about doing something like this:

kwargs['profile_id'] = kwargs.get('profile_id') or 'something1'
Anthony
  • 931
  • 1
  • 13
  • 30
  • 1
    Try defining a default dictionary, with the keys and their default values. Then do `adict.update(kwargs)`. The `kwargs` values will overwrite the defaults where given. – hpaulj Sep 17 '19 at 18:40

2 Answers2

5

.get() has an optional second argument, which is the default value.

kwargs['profile_id'] = kwargs.get('profile_id', 'something1')

Also, instead of calling get() in your if statements, you can use

if 'profile_id' not in kwargs:

Note that these solutions won't replace explicit None values in the dictionary.

You could use a dictionary of defaults for all the fields, and merge them.

defaults = {"profile_id": "something1", "status": "something2", ...}
kwargs = {**defaults, **kwargs}

See How to merge two dictionaries in a single expression?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Yes, but what if the value for the key is None as well? In your code it stays as `None`, but in the original code it gets replaced as well – Ralf Sep 17 '19 at 18:21
  • @Ralf I've updated the answer to mention this caveat. – Barmar Sep 17 '19 at 18:25
2

One option could be to use a loop to write the if only once:

for k, new_val in [
    ('profile_id', 'something1'),
    ('status', 'something2'),
    ...
]:
    if kwargs.get(key) is None:
        kwargs[key] = new_val

Note: this will also replace the value for key with new_val in cases where key is present with value None in kwargs.

Ralf
  • 16,086
  • 4
  • 44
  • 68