Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument unpacking with custom __getitem__ method never terminates

Tags:

python

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())
like image 951
kosciej16 Avatar asked Oct 12 '25 10:10

kosciej16


1 Answers

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.

like image 147
juanpa.arrivillaga Avatar answered Oct 15 '25 00:10

juanpa.arrivillaga