DEV Community

Discussion on: Dead Simple Python: Loops and Iterators

 
pkwhaley profile image
Pete (he/him)

I noticed this error case while reading through the article as well. In the sake of learning I just couldn't move on and ignore it.

Here is my fix. I am sure there are better ways to accomplish this, so please critique and let me know how I could better accomplish this.

The only thing I changed was the next method as follows:

    def __next__(self):
        if self._index == self._max:
            raise StopIteration
        else:
            _number, _name = self._roster[self._index]
            if _name in self._classified:
                self._roster.pop(self._index)
            r = self._roster[self._index]
            self._index += 1
            return r
Thread Thread
 
codemouse92 profile image
Jason C. McDonald

Hey, that's pretty good. However, my only concern is that it would delete the internally stored information about the classified agent (which we don't want).

Thread Thread
 
pkwhaley profile image
Pete (he/him)

Ah, good point.

Take 2 [move classified to end of _roster]:

            if _name in self._classified:
                self._roster.append(self._roster.pop(self._index))
            r = self._roster[self._index]

Thanks so much for these articles and for being so responsive. They are written very well , engaging, and a great resource.

Thread Thread
 
codemouse92 profile image
Jason C. McDonald

If I were going to fix this problem (which I may well do soon -- I have to take another pass through this material when writing the book), I would actually define the __getitem__() function instead, as that controls the behavior of the [] operator.

This all comes down to separation of concerns. It shouldn't be the responsibility of __next__() to mutate the internal data to obscure information. It's only job should be to determine whether it exposes that information, and how.

Of course, in all honesty, there's nothing preventing a direct call to agents._roster[1] (Python has no private variables). If we were going to obfuscate or remove classified data, that should really occur on the add_agent() function.