Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way to write this in Python?

I want to append 'status' to the dict value indexed by 'update_fields' or add ['status'] as a value to kwargs indexed by 'update_fields' if that key isn't present.

kwargs.setdefault('update_fields', kwargs.get('update_fields', []).append('status'))

It's either this or about 3 lines of code, surely python can do better than this!

like image 801
boatcoder Avatar asked Dec 14 '25 00:12

boatcoder


2 Answers

get and setdefault are essentially two methods of doing the same thing; putting them together is repeating yourself. The only difference between get and setdefault is that setdefault sets the value if the default doesn't exist. After that, they are identical semantically.

So this part:

kwargs.get('update_fields', [])

..is redundant. setdefault sets the default (and returns it, like get) if the dictionary doesn't have a value for that key yet, otherwise it just looks up the value associated with the key.

So all you need is:

kwargs.setdefault('update_fields', []).append('status')
like image 83
roippi Avatar answered Dec 15 '25 12:12

roippi


You don't need the kwargs.get() bit, setdefault only sets the value if it's not already there, you can just write:

kwargs.setdefault('update_fields', []).append('status')
like image 32
Alex Gaynor Avatar answered Dec 15 '25 12:12

Alex Gaynor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!