[Python-ideas] Suggestions: dict.flow_update and dict.__add__

Christopher Barker pythonchb at gmail.com
Tue Mar 12 11:59:44 EDT 2019


On Fri, Mar 8, 2019 at 1:52 AM Jonathan Fine <jfine2358 at gmail.com> wrote:

> I've just learnt something new. Look at
>
>     >>> from operator import iadd
>     >>> lst = [1, 2, 3]
>     >>> iadd(lst, 'hi')
>     [1, 2, 3, 'h', 'i']
>     >>> lst
>     [1, 2, 3, 'h', 'i']
>
> This shows that the proposals dict.flow_update and dict.__iadd__ are
> basically the same. (I think this is quite important for understanding
> the attraction of fluent programming. We ALREADY like and use it, in
> the form of augmented assignment of mutables.)
>

well, no -- the fact that __iadd__ acts like it does is essentially an
accident of implementation, and calling __iadd__ directly is frowned upon
(and I'm not totally sure if it is guaranteed to keep working that way by
the language spec). And, in fact, it DOESN'T act like flow_merge method --
as it both mutates the original object, and returns itself -- which I think
is a no-no in fluent programming, yes? (certainly in functional programming)

In [10]: list1 = [1,2,3]

In [11]: list2 = [4,5,6]

In [12]: list3 = list1.__iadd__(list2)

In [13]: list3
Out[13]: [1, 2, 3, 4, 5, 6]

In [14]: list1
Out[14]: [1, 2, 3, 4, 5, 6]

In [15]: list1 is list3
Out[15]: True


This also shows that
>    combined = defaults.copy()
>    combined.update(options)
> could, if the proposal is accepted, be written as
>    defaults.copy().__iadd__(options)
>

did you mean:

combined = defaults.copy().__iadd__(options)

because the way you wrote it, you are making a copy, mutating it, and then
throwing it away...

in which case, yes it could, but it would not be recommended, and I can't
see the advantage of it over:

combined = defaults + options

or even, if you REALLY want to use __ methods:

combined = defaults.__add__(options)


In [17]: list3 = list1.__add__(list2)

In [18]: list1
Out[18]: [1, 2, 3]

In [19]: list3
Out[19]: [1, 2, 3, 4, 5, 6]


> I got the idea from the withdrawn PEP (thank you, Nick Coghlan, for
> writing it):
> PEP 577 -- Augmented Assignment Expressions
> https://www.python.org/dev/peps/pep-0577/
>

Interestingly (to me) it was withdrawn for different reasons than what I
would think -- mutating and assigning at once is dangerous.

-CHB


-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190312/af485e86/attachment-0001.html>


More information about the Python-ideas mailing list