Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #18717

Re: classes and __iter__

References <CA+oqfxRF4Gm=hfWsHRZ0mG-v=QSuNS+ED72x+d2b-5CO6BnaqQ@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-01-09 16:20 -0700
Subject Re: classes and __iter__
Newsgroups comp.lang.python
Message-ID <mailman.4556.1326151265.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jan 9, 2012 at 3:51 PM, david.garvey@gmail.com
<david.garvey@gmail.com> wrote:
> ...     def __iter__(self):
> ...         return iter(self.keylist, self.d)

This method is incorrect.  The 2-argument form of iter() is very
different from the 1-argument form.  Whereas the 1-argument form takes
an iterable, the 2-argument form takes a callable and a sentinel
value.  In that case, iter() attempts to call the callable until the
sentinel is returned.  In your code, it would attempt to call the
keylist (which would fail with a TypeError) until it returned the
dictionary as a result.  This would be more in line with what you're
trying to do:

def __iter__(self):
    for key in self.keylist:
        yield key, self.d[key]


>>>> for key in helo.keylist:
> ...     print "Key:%s Value:%s" %(key,helo.d[key])

Note that this works because you're not actually using the class's
__iter__ method here.  You're iterating over the keylist directly, not
over the containing class instance.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: classes and __iter__ Ian Kelly <ian.g.kelly@gmail.com> - 2012-01-09 16:20 -0700

csiph-web