[Python-ideas] Implement __add__ for set and frozenset

George Sakkis george.sakkis at gmail.com
Tue Jun 3 04:06:51 CEST 2008


On Mon, Jun 2, 2008 at 9:28 PM, Brandon Mintern <bmintern at gmail.com> wrote:

>
> I thought max was implemented using += (i.e. it usually starts at 0
> and uses += on each item in the iterable). If so, implementing **
> _iadd_ ** would result in exactly the code you posted. I realize that
> I said __add__ in the first place, but __iadd__ is really what I
> meant.
>

No, it uses __add__:

$ python -c "
class Set(set): __iadd__=set.__ior__
sum([Set([1]), Set([2])], Set())
"
Traceback (most recent call last):
  File "<string>", line 3, in <module>
TypeError: unsupported operand type(s) for +: 'Set' and 'Set'

You can easily see the quadratic behavior of __add__:

$ python -m timeit -s "class Set(set): __add__=set.__or__" "sum(
(Set(range(i*10, i*10+10)) for i in xrange(100)), Set())"
100 loops, best of 3: 2.4 msec per loop
$ python -m timeit -s "class Set(set): __add__=set.__or__" "sum(
(Set(range(i*10, i*10+10)) for i in xrange(200)), Set())"
100 loops, best of 3: 8.04 msec per loop
$ python -m timeit -s "class Set(set): __add__=set.__or__" "sum(
(Set(range(i*10, i*10+10)) for i in xrange(400)), Set())"
10 loops, best of 3: 33.3 msec per loop
$ python -m timeit -s "class Set(set): __add__=set.__or__" "sum(
(Set(range(i*10, i*10+10)) for i in xrange(800)), Set())"
10 loops, best of 3: 141 msec per loop
$ python -m timeit -s "class Set(set): __add__=set.__or__" "sum(
(Set(range(i*10, i*10+10)) for i in xrange(1600)), Set())"
10 loops, best of 3: 684 msec per loop


George
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20080602/c64d49d3/attachment.html>


More information about the Python-ideas mailing list