
On 25.05.2016 20:42, Steven D'Aprano wrote:
There's no need to unpack the entire dict, you can grab only the keys you need:
width, height = **prefs
# like width = prefs['width'] height = prefs['height']
That's not the same behavior as it is for tuple unpacking. As a new user, I would expect them to work the same way. If I want to dismiss the remainder of the dict, I'd rather consider an explicit approach: width, height = **prefs # just those values width, height, *r = **prefs # r captures the rest This gives me two benefits: 1) I can further work with r from which width and height are extracted 2) a convenient way of verifying that a dict only contains certain values and extracting those at the same time
Sure, you are forced to use the same variable names as the keys, but that's what you will probably do most of the time. You're not likely to write:
foo = prefs['width'] bar = prefs['height']
although you might write:
zip_code = prefs['zip code']
but probably shouldn't. (Just use 'zip_code' as the key.)
"just use 'zip_code' as the key" won't do it when you have no influence on the data. I might remind you that most engineers are no gods who can change everything at their whim.
[...] If you twist my arm and force me to come up with syntax for a "change of variable name", I'd consider:
Rest assured I will twist your arm very hard. ;) Also rest assured that we use non-string keys on a regular basis. Maybe, it's just me but I still tend to think that using unquoted strings should be reserved for attribute unpacking.
[...]
If the target on the left has a colon, it is an identifier followed by key. The identifier can be any valid reference, including dots and [] subscripts. The key must be a string:
identifier:'key'
I would rather turn it around. It feels weird to have the "key" on the right side. One additional drawback of this solution is the fact that the "value" part of the colon is already taken. So, value matching like done in Erlang is not possible. OTOH, this applies to tuple unpacking in its current form as well Best, Sven