[Tutor] iteritems() vs items()

Tim Johnson tim at johnsons-web.com
Sun Nov 13 18:25:54 CET 2005


* Kent Johnson <kent37 at tds.net> [051112 20:33]:
> Tim Johnson wrote:
> >I need to get up to speed on iterators. I learned python 1.5~ via
> >Alan G's book ...
> >For an example, I've written a subclass of dict where keys are kept in
> >a ordered fashion is a list called __keys:
> >
> >#Here is my items function:
> >    def items(self):
> >    """ Return all pairs in order of addition"""
> >    return [(key,self.__dict[key]) for key in self.__keys]
> >
> >#And here is my iteritems function (currently does exactly the same thing)
> >    def iteritems(self):
> >        """ At this implementation, does exactly the same thing as 
> >        method items()"""
> >        for key in self.__keys:
> >            yield (key,self.__dict[key])
 
  Ah. I did it right without know what I was doing. 
  Now if I assign a value to the iteritems method, as in 
  it = s.iteritems()
  I get an object of <dictionary-iterator object at 0x407e3a40>
  and dir(it) shows that (it) has one public method - next().

  Question: Can one subclass an iterator object?
  thanks for making this a little clearer.
  
  tim
  
> I think you have it right. Your two methods don't do the same thing - 
> items() returns a list of key, value pairs; iteritems() returns a generator 
> which yields key, value pairs. This is the correct behaviour.
> 
> Kent
> -- 
> http://www.kentsjohnson.com

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com


More information about the Tutor mailing list