[Python-ideas] Suggestions: dict.flow_update and dict.__add__
Jonathan Fine
jfine2358 at gmail.com
Tue Mar 5 03:48:44 EST 2019
SUMMARY
Instead of using dict + dict, perhaps use dict.flow_update. Here,
flow_update is just like update, except that it returns self.
BACKGROUND
There's a difference between a sorted copy of a list, and sorting the
list in place.
>>> items = [2, 0, 1, 9]
>>> sorted(items), items
([0, 1, 2, 9], [2, 0, 1, 9])
>>> items.sort(), items
(None, [0, 1, 2, 9])
In Python, mutating methods generally return None. Here, this prevents
beginners thinking their code has produced a sorted copy of a list,
when in fact it has done an in-place sort on the list. If they write
>>> aaa = my_list.sort()
they'll get a None error when they use aaa.
The same goes for dict.update. This is a useful feature, particularly
for beginners. It helps them think clearly, and express themselves
clearly.
THE PROBLEM
This returning None can be a nuisance, sometimes. Suppose we have a
dictionary of default values, and a dictionary of use supplied
options. We wish to combine the two dictionaries, say into a new
combined dictionary.
One way to do this is:
combined = defaults.copy()
combined.update(options)
But this is awkward when you're in the middle of calling a function:
call_big_method(
# lots of arguments, one to a line, with comments
arg = combined, # Look up to see what combined is.
# more arguments
)
USING +
There's a suggestion, that instead one extends Python so that this works:
arg = defaults + options # What does '+' mean here?
USING flow_update
Here's another suggestion. Instead write:
dict_arg = defaults.copy().flow_update(options) # Is this clearer?
IMPLEMENTATION
Here's an implementation, as a subclass of dict.
class mydict(dict):
def flow_update(self, *argv, **kwargs):
self.update(*argv, **kwargs)
return self
def copy(self):
return self.__class__(self)
A DIRTY HACK
Not tested, using an assignment expression.
dict_arg = (tmp := defaults.copy(), tmp.update(options))[0]
Not recommend.
--
Jonathan
More information about the Python-ideas
mailing list