Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement iteritems function for my custom iterator?

The objective of the following program is to learn python generators and iterator implementation in order to understand Python magic methods.

I'm stuck implementing the iteritems() function. Also, I want to know whether I'm going on right direction or I'm conceptually wrong in understanding of python magic methods.

import random

class Random(object):
    """ generate randomised int of specified length --> [r1, r2, r3....] """

    def __init__(self, length = 1, rand_range = 100):
        self.index = 0
        self.generated_range = []
        self.length = length if str(length).isdigit() else 1
        self.rand_range = rand_range if str(rand_range).isdigit() else 100

    def __iter__(self): return self

    def next(self):
        if self.index < self.length:
            item = random.randrange(0, self.rand_range)
            self.generated_range.append(item)
            self.index += 1
            return item
        raise StopIteration

    def __eq__(self, obj):
        if self.length == obj.length and self.rand_range == obj.rand_range:
            return True
        return False

    def __len__(self):
        return self.length

    def __contains__(self, item):
        if not self.index == self.length:
            while self.next(): continue
        if item in self.generated_range:
            return True
        return False

    def __getitem__(self, key):
        if key in self.generated_range:
            return key * 100
        raise KeyError

    def __setitem__(self, key, value):
        raise NotImplemented

    def __delitem__(self, key):
        raise NotImplemented

    def iteritems(self):
        if not self.index == self.length:
            while self.next(): continue
        for item in self.generated_range:
            yield item

if __name__ == '__main__':
    r1 = Random(10)
    print [ r for r in r1]
    print 10 in r1
    r2 = Random(20)
    print r2.iteritems()

CodePAD link

like image 783
necromancer Avatar asked Oct 26 '10 05:10

necromancer


Video Answer


1 Answers

iteritems is supposed to return a sequence of (key, val) pairs for a dictionary, so I don't think it's appropriate for your class. If you created a descendant of UserDict, then there might be a case to override it.

If you do override iteritems, you should do so by yielding key, value pairs.

Poor programmer's override:

def iteritems(self):
    return iter([(x[0], x) for x in "alpha bravo charlie".split()])
like image 61
Ryan Ginstrom Avatar answered Oct 04 '22 01:10

Ryan Ginstrom