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


Groups > comp.lang.python > #18717 > unrolled thread

Re: classes and __iter__

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2012-01-09 16:20 -0700
Last post2012-01-09 16:20 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#18717 — Re: classes and __iter__

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-01-09 16:20 -0700
SubjectRe: classes and __iter__
Message-ID<mailman.4556.1326151265.27778.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web