Dictionaries are used and abused for all sorts of things, but they are especially important in Python - after all Python objects are syntactic sugar on top of dictionaries. Some of the use-cases involve merging multiple dictionaries into a single one - this comes handy in case overrides need to be supported. For instance, let’s say we are passing workflow metadata across different services. Before sending this metadata to telemetry service, we may need to merge existing metadata with ones from the current service. Usually it looks something like
Well, I guess it’s not too bad… But what if there was a better way? Python has tons of ways to do the same thing, so we are in luck and we can use dictionary unpacking
And since Python 3.9 we have yet another way using merge operator
So which one is better? It’s a trick question - better for what? Syntax is usually a matter of taste, even though I’d imagine majority would prefer merge operator, but what if there was a more objective measure? How about performance?
And looks we have our winner - merge operator is not only super concise and readable, it’s also the fastest - in fact it’s ~2X faster than using dictionary update.
To some extent it shouldn’t come as total surprise. A quick glance over bytecode is enough to plant such suspicion
Merge operator approach has the fewest number of bytecode instructions, so if nothing else, interpreter has fewer instructions to deal with. Reduced instruction count doesn’t always translate into faster interpretation, because not all instructions are created equal, especially when it comes to those that are implemented natively in C and those that spend more time in Python, but, fortunately, in case of merge operator - things are both compact and fast.
nice!