What does iterable mean in Python?

First I want to clarify, I am NOT asking what an "iterator" is.

Thus, the term "iterable" is defined in the Python doc :

iteration An
object that can return its elements one at a time. Examples of iterations include all sequence types (such as list, str, and tuple) and some non-sequence types such as dict, file objects, and objects of any classes that you define using __ iter __ () or __getitem __ ()method. Iterators can be used in a for loop and in many other places where a sequence is required (zip (), map (), ...). When the object is repeated passed as an argument to the iter () built-in function, it returns an iterator for the object. This iterator is good for one pass over multiple values. When using iterations, it is usually not necessary to call iter () or process the iterator objects yourself. for the operator, does this automatically for you, creating a temporary unnamed variable to hold the iterator throughout the loop. See also iterator, sequence, and generator.

As other people suggested , use isinstance(e, collections.Iterable)is the most pythonic way to check if an object is iterable.
So I did some tests with Python 3.4.3:

from collections.abc import Iterable

class MyTrain:
    def __getitem__(self, index):
        if index > 3:
            raise IndexError("that enough!")

        return index

for name in MyTrain():
    print(name)  # 0, 1, 2, 3

print(isinstance(MyTrain(), Iterable))  # False

: MyTrain __getitem__, , , .

__getitem__ __iter__:

from collections.abc import Iterable

class MyTrain:    
    def __iter__(self):
        print("__iter__ called")
        pass

print(isinstance(MyTrain(), Iterable))  # True

for name in MyTrain():
    print(name)  # TypeError: iter() returned non-iterator of type 'NoneType'

"" , , .

- ?

+4
3

, , , __getitem__ , , Iterable.

, , ( Iterable, __iter__) isinstance issubclass ABC, . , , , .

. PEP-3119, ABC.


isinstance(e, collections.Iterable), ,

; duck-typing . , TypeError, , , . , , , .


, , , , . iter docs, , , :

, ( __iter__()), ( __getitem__() , 0).

, , , " ", isinstance(thing, Iterable). , ", " :

isinstance(thing, (Iterable, Sequence))

, __len__ __getitem__ " " Sequence.

+2

. abc.Iterable, , , Python . - - .

0

Iterable - - ( -), . python? in, __iter__ . , , __iter__, in Iterable.

, "" , , , (, , isinstance, - )

hasattr(train, '__iter__')

, .

__iter__, , , , .

. - , __iter__, , - , in. : - NumberList each, python.

class NumberList:

     def __init__(self, values):
         self.values = values

     def each(self):
         return self.values
-1
source

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


All Articles