'TypeError: iter() returned non-iterator of type 'NoneType'
from collections.abc import Iterable
from collections.abc import Iterator
class MyList(object):
def __init__(self): self.Container = [11, 22, 33]
def add(self, item): self.Container.append(item)
def __iter__(self): return MyIterator
class MyIterator(object):
def __init__(self): pass
def __next__(self): pass
def __iter__(self): pass
mylist = MyList()
mylist_iter = iter(mylist)
print(isinstance(mylist, Iterable))
print(isinstance(mylist, Iterator))
print(isinstance(mylist_iter, Iterable))
print(isinstance(mylist_iter, Iterator))
ERRO! Traceback (most recent call last): File "D:\Python\t.py", line 19, in mylist_iter = iter(mylist) TypeError: iter() returned non-iterator of type 'type'
Why & How to solve this problem?
Solution 1:[1]
You need parenthesis after MyIterator here in order to instantiate a MyIterator object:
def __iter__(self): return MyIterator()
You were returning a "type" object (MyIterator) instead of an actual instance of the MyIterator class.
A simple example:
# init an actual int type variable
>>> d = int()
>>> type(d)
<class 'int'> # its type is "int"
>>> d
0
# init what is essentially an alias for the int class
>>> d = int
>>> type(d)
<class 'type'> # its type is "type"
>>> d
<class 'int'>
# we can even use "d" in place of "int" now to initialize an integer
>>> d(234)
234
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
