Could someone explain what is going on under the hood and why this program does not finish?
class A:
def __getitem__(self, key):
return 1
print(*A())
This program doesn't finish because the class you defined is iterable, using the old sequence iteration protocol. Basically, __getitem__
is called with integers increasing from 0, ..., n until an IndexError
is raised.
>>> class A:
... def __getitem__(self, key):
... return 1
...
>>> it = iter(A())
>>> next(it)
1
>>> next(it)
1
>>> next(it)
1
>>> next(it)
1
You are unpacking an infinite iterator, so eventually you'll run out of memory.
From the iter
docs:
Without a second argument, object must be a collection object which supports the iteration protocol (the
__iter__()
method), or it must support the sequence protocol (the__getitem__()
method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With