Python iter over dict-like object

 class Test(object):

     def __init__(self, store):
         assert isinstance(store, dict)
         self.store = store

     def __getitem__(self, key):
         return self.store[key]

I am trying to use this class. In this document , which implements the __getitem__, should be sufficient to use in my class Test. In fact, when I try to do this, it does not tell me that I cannot, but I have a KeyError:

In [10]: a = Test({1:1,2:2})

In [11]: for i in a: print i
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-8c9c9a8afa41> in <module>()
----> 1 for i in a: print i

<ipython-input-9-17212ae08f42> in __getitem__(self, key)
      4         self.store = store
      5     def __getitem__(self, key):
----> 6         return self.store[key]
      7

KeyError: 0
  • Do you know where this 0 comes from? (what happens under the hood)

I know I can solve this problem by adding the __iter__ function:

def __iter__(self):
    return dict.__iter__(self.store)
  • Is this the best way to solve this problem? (I could also inherit from the dict class).
+4
source share
1 answer

You missed the key statement in the found documentation:

. [...] [I] f ( ), IndexError .

: for , IndexError, .

. , , .

Python ; . :

, __getitem__() __len__(), . [...] , dict __getitem__() __len__(), , , , .

, , , for *. , , __getitem__, , 0 , IndexError . Python :

def getitem_iterator(obj):
    getitem = type(obj).__getitem__  # special method, so on the type
    index = 0
    try:
        while True:
            yield getitem(obj, index)
            index += 1
    except IndexError:
        # iteration complete
        return

C, . PySeqIter_Type.

__iter__ ; , . , ( iter() function ):

def __iter__(self):
    return iter(self.store)

* , for . for iter(obj), , __iter__.

+7

Source: https://habr.com/ru/post/1660927/


All Articles