nick_v1
nick_v1

Reputation: 1664

Python Generator/Iterator

I am working on improving my python and getting up to speed on generators. I have an object that I am working on to process a series of events. I want the list of events to be pulled sequentially and through various methods. I want to use generators for this purpose (I know I can write something else to do this without them).

Here is the sample code that I've been working on:

def _get_next_event():
    def gen():
        for i,event in enumerate(range(1,10)):
            yield event

    iterator = gen()
    def run():
        return iterator

    run.next = iterator.__next__
    return run

t = _get_next_event()
t.next()
for x in t():
    if x < 5:
        print(x)
    else:
        break

t.next()

This lets me do a for loop on the events as well as pull next one individually via function's next method.

I am implementing this in my class, it looks like this:

def _get_next_event(self):
    def gen():
        print(self.all_sessions)
        for event in self.all_sessions:
            yield event['event']
    iterator = gen()
    def run():
        return iterator
    run.next = iterator.__next__
    return run

However, before it works in the class I have to run it, for example before the for loop I have one of these:

self._get_next_event = self._get_next_event()

I think there should be a more elegant way of doing this... what am I missing?

Upvotes: 0

Views: 135

Answers (1)

Kevin
Kevin

Reputation: 30151

Usually, generators are... not written like that.

Ordinarily, you'd just use yield in the top-level function:

def _get_next_event():
    for i,event in enumerate(range(1,10)):
        yield event

You can then just write this:

for event in _get_next_event():
    # do something with event

Perhaps you had some reason for doing it the way you've shown, but that reason is not evident from the code you've posted.

(for the record, I'm assuming your generator does not literally look like that, or else I'd tell you to change the whole function body to return range(1, 10))

Upvotes: 1

Related Questions