Is there any way to detect whether a generator’s __iter__ is called with list()? As I understand it, list(obj) will call __iter__; however, in the case of an infinite generator, I want it to return an error.
For example, I have the following generator:
def gen():
while 1:
yield 1
Since calling list(gen) will result in an infinite loop, I want to make it so that it returns an error. Is there a way to do this?
There is no sensible way to do this. You might be able to hijack the stacktrace, but it’ll be ugly and error-prone.
(Obviously, what you’re trying to do is not how an iterable is expected to behave in Python, which is another good reason not to do it.)
Besides, it won’t loop forever, but keep trying to allocate memory for the list. As soon as this fails, a
MemoryErrorwill be thrown and the interpreter may or may not recover.