a_iterable = IterableObjc() assert isinstance(a_iterable, abc.Iterable) # no exception assert isinstance(a_iterable, Iterable) # no exception abc.Iterable is Iterable # collection.Iterable is the same as a_iterable
True
‘for’ syntax is able to be used for iterable.
python
1
Iterable_instance = IterableObjc()
python
1 2
for i in Iterable_instance: print(i)
1
2
3
Iterable could be also understood as any accepted object by iter() function.
_getitem_() is another way to define a Iterable object.
note: StopIteration() exception has to be raised in _getitem_() function, otherwise infinite loop will be triggered when ‘for’ syntax is used!
for syntax is able to call iter() method for an iterable object, which transfers the iterable to a generator, and then call next(generator_object) until the StopIteration() exception is raised.
a
b
c
d
e
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-87-2fbad4156275> in <module>()
4 print(next(iterator_string))
5 print(next(iterator_string))
----> 6 print(next(iterator_string)) # raise StopIteration() exception
StopIteration:
python
1 2 3
iterator_string = IteratorStr('abcde') for i in iterator_string: print(i)
a
b
c
d
e
Generator
function with ‘yield’ syntax is called a generator function.
python
1 2 3
defgenerator_function(): for i in range(3): yield i
A generator function has to be ‘instantiated’. The syntax looks like the instance of the generator function. But actually it is creating a generator from the generator function yield statement.
python
1
gen = generator_function()
python
1
type(gen)
generator
python
1 2
for i in gen: print(i)
0
1
2
A generator will automatically have the _next_ method implemented