set and dict iteration

Ian Kelly ian.g.kelly at gmail.com
Thu Aug 16 19:43:55 EDT 2012


On Thu, Aug 16, 2012 at 5:11 PM, Dave Angel <davea at dejaviewphoto.com> wrote:
> There's an enormous difference between type errors, which affect the low
> level dispatch, and checking for whether a dict has changed and may have
> invalidated the iterator.  If we were really going to keep track of what
> iterators are tracking a given dict or set, why stop there?  Why not
> check if another process has changed a file we're iterating through?  Or ...

How does this affect low-level dispatch (Python 2.7)?

>>> class Foo(object):
...     def bar(self):
...         return self
...
>>> Foo().bar()
<__main__.Foo object at 0x00CBEAB0>
>>> Foo.bar(Foo())
<__main__.Foo object at 0x00CC9390>
>>> Foo.bar(object())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as
first argument (got object instance instead)

There is no low-level need for this TypeError -- it's purely a case of
not letting the developer shoot himself in the foot.  Although to be
honest the interpreter doesn't give quite enough rope (to mix
metaphors) in this case, and I'm glad for the sake of duck typing that
they removed this particular error in Python 3.

With regard to key insertion and deletion while iterating over a dict
or set, though, there is just no good reason to be doing that
(especially as the result is very implementation-specific), and I
wouldn't mind a more complete low-level check against it as long as
it's not too expensive (which is not clearly the case with the current
suggestion at all).



More information about the Python-list mailing list