Skip to content
This repository was archived by the owner on Feb 6, 2025. It is now read-only.
This repository was archived by the owner on Feb 6, 2025. It is now read-only.

Bad __next__ implementations #21

@sad2project

Description

@sad2project

I read your blog and double-checked the code on here, and they both have the same issue. You implement the __next__() methods like this:

def __next__(res):
    return next(res)

I don't know what you think this is doing, but it will cause a recursive error. The reason you probably haven't had any problems is because your __iter__() method is returning an iterator/iterable, which is what is typically getting the next() calls on it, rather than the instances of your classes.

For some reason, you name the self parameter of __next__() as res, and I think you think you're actually getting the result of the call to __iter__() passed into that method, but you're not. If this method is called, it's because someone called next() with an instance of your class instead of with whatever was returned from __iter__(). And then your method simply calls next() on self (which you named res), which will cause this method to be called again, creating an infinite recursion.

To prove this, simply write next(lazymap(lambda x: x, [])). Under normal circumstances, it would raise a StopIteration for trying to get the next item of an empty iterable. But this will stall and give you a recursion error. Personally, my recommendation is simply to remove your __next__() methods. That will make them iterables and not poorly designed iterators, and most people will use them correctly. The above code will simply complain about there not being a __next__() method, which people will figure out.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions