[Python-ideas] Adding "+" and "+=" operators to dict

Chris Angelico rosuav at gmail.com
Sat Feb 14 06:28:36 CET 2015


On Sat, Feb 14, 2015 at 3:38 PM, Chris Barker <chris.barker at noaa.gov> wrote:
> In [25]: (l1 + l2) += [3]
>   File "<ipython-input-25-b8781c271c74>", line 1
>     (l1 + l2) += [3]
> SyntaxError: can't assign to operator
>
> which makes sense -- the LHS is an expression that results in a list, but +=
> is trying to assign to that object. HOw can there be anything other than a
> single object on the LHS?

You'd have to subscript it or equivalent.

>>> options = {}
>>> def get_option_mapping():
    mode = input("Pick an operational mode: ")
    if not mode: mode="default"
    if mode not in options: options[mode]=defaultdict(int)
    return options[mode]
>>> get_option_mapping()["width"] = 100
Pick an operational mode: foo
>>> options
{'foo': defaultdict(<class 'int'>, {'width': 100})}

Sure, you could assign the dict to a local name, but there's no need -
you can subscript the return value of a function, Python is not PHP.
(Though, to be fair, PHP did fix that a few years ago.) And if it
works with regular assignment, it ought to work with augmented... and
it does:

>>> get_option_mapping()["width"] += 10
Pick an operational mode: foo
>>> get_option_mapping()["width"] += 10
Pick an operational mode: bar
>>> options
{'foo': defaultdict(<class 'int'>, {'width': 110}), 'bar':
defaultdict(<class 'int'>, {'width': 10})}

The original function gets called exactly once, and then the augmented
assignment is done using the resulting dict.

ChrisA


More information about the Python-ideas mailing list