rsalmei / alive-progress

A new kind of Progress Bar, with real-time throughput, ETA, and very cool animations!
MIT License
5.53k stars 206 forks source link

Use next with `alive_it' object #132

Closed shadowrylander closed 2 years ago

shadowrylander commented 2 years ago

Hello!

If a certain keyword is passed in, my module bakery returns an iterable (I think? Still confused with those) wrapped in your alive_it function; however, if I were to use for on it, such as for item in bakery(alive = True), I get TypeError: '__AliveBarIteratorAdapter' object is not an iterator; this is the relevant code, translated from hylang:

def  __iter__(self):
    self.n = 0
    self.output = self.getOutput() # returns `alive_it' wrapped object
    return self
def __next__(self):
    try:
        outputLen = len(self.output)
    except TypeError:
        return next(self.output)
    else:
        if self.n < outputLen:
            self.n += 1
            return self.output[self.n - 1]
        else:
            raise StopIteration

How would I go about fixing this?

Thank you kindly for the help!

rsalmei commented 2 years ago

Hello @shadowrylander

Yeah, I think you are mixing Iterables and Iterators. You can't get "the next item" from an Iterable, only from an Iterator. Even from a simple range you can't get a "next" item, look:

image

It's the same thing with my AliveIt adapter:

image

It's kinda tricky to implement both __iter__ and __next__, and you probably don't need that! Together they serve a different purpose, which is not this scope. But you should implement this using only __iter__, and make it a generator, where you yield the elements you need. You can even use yield from alive_it(), and let Python work for you.

shadowrylander commented 2 years ago

So would something like this in __iter__ work?

if isinstance(self.output, __AliveBarIteratorAdapter):
    yield from self.output
else:
    return self
shadowrylander commented 2 years ago

Ahp; wait; never mind. Just turn the whole damn thing into a generator using yield from. Thanks for this new fun concept to play with! 😹😹😹😹 And thank you kindly for all the help as well!

rsalmei commented 2 years ago

You're welcome 👍