Home > Back-end >  Sequence with no __iter__?
Sequence with no __iter__?

Time:02-04

Is there any built-in type in Python 3 which implements __getitem__ but does not implement the __iter__ method?

I think in Python 2 the str type was this case but now in Python 3, str type has an __iter__ method.

CodePudding user response:

memoryview seems to be the only one:

>>> import builtins
>>> [b for b in dir(builtins) 
     if isinstance(t := getattr(builtins, b), type) 
        and hasattr(t, '__getitem__') 
        and not hasattr(t, '__iter__')]
['memoryview']

There might be some standard modules that aren't loaded by default that have types like this.

  • Related