Launch:
class DontList(object): def __getitem__(self, key): print 'Getting item %s' % key if key == 10: raise KeyError("You get the idea.") return None def __getattr__(self, name): print 'Getting attr %s' % name return None list(DontList())
Produces the following:
Getting attr __length_hint__ Getting item 0 Getting item 1 Getting item 2 Getting item 3 Getting item 4 Getting item 5 Getting item 6 Getting item 7 Getting item 8 Getting item 9 Getting item 10 Traceback (most recent call last): File "list.py", line 11, in <module> list(DontList()) File "list.py", line 4, in __getitem__ if key == 10: raise KeyError("You get the idea.") KeyError: 'You get the idea.'
How can I change this to get [] , while maintaining access to these keys [1] , etc.?
(I tried inserting def __length_hint__(self): return 0 , but that doesn't help.)
My real use case: (for reading, if this is useful, feel free to ignore the past)
After applying a specific patch for a tacit search, I found an unpleasant side effect for my patch. Set __getattr__ to my Undefined class, which returns a new Undefined object. Unfortunately, this means list(iniconfig.invalid_section) (where isinstance(iniconfig, iniparse.INIConfig) ) does this (put in print in __getattr__ and __getitem__ ):
Getting attr __length_hint__ Getting item 0 Getting item 1 Getting item 2 Getting item 3 Getting item 4
Et and endlessly.
python
Chris morgan
source share