Confusion about iterator types
Martin von Loewis
loewis at informatik.hu-berlin.de
Sun Aug 12 11:06:46 EDT 2001
Kirby Urner <urner at alumni.princeton.edu> writes:
> >>> mylist = [1,2,3,4]
> >>> myiter = iter(mylist)
>
> I then get:
>
> >>> type(myiter)
> <type 'iterator'>
>
> But 'iterator' by itself has no corresponding type in types.
It sure does:
>>> import types
>>> type(myiter) is types.SequenceIterType
1
> If I use the isinstance() method, I can confirm that myiter is a
> SequenceIterType, but shouldn't it just tell me that?
What way of telling do you expect? Something about the name of the
type? Watch this
>>> types.DictionaryType.__name__
'dictionary'
>>> types.FunctionType.__name__
'function'
So in general, the __name__ of a type is only roughly related to the
name to which it is bound in the types module.
> Shouldn't type(foo) return a type name that more closely matches its
> type in types? Why not have?
>
> >>> type(myiter)
> <type 'sequence-iter'>
I personally see no advantage in having it renamed, if you do, feel
free to submit a feature request at sf.net/projects/python. If you can
point to an actual problem that the current name causes, you should
make it a bug report.
> Also, some clarification re the below would be helpful:
>
> >>> def f(n): return n*n
>
> >>> callable(f)
> 1
> >>> k = iter(f,10)
> >>> type(k)
> <type 'callable-iterator'>
> >>> k()
> Traceback (most recent call last):
> File "<pyshell#142>", line 1, in ?
> k()
> TypeError: object is not callable: <callable-iterator object at 00B6D10C>
It is an iterator that iterates over a callable object; the iterator
itself is not callable. So you are supposed to do
>>> k.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: f() takes exactly 1 argument (0 given)
An iterator object has a .next() method to retrieve a value. As you
can see, the iterator tries to call f with no arguments, so the
callable shouldn't expect any arguments, either. A meaningful
application of this is
>>> data = [1,4,10,20]
>>> def fetch():
... if len(data):
... result = data[0]
... data[0:1] = []
... return result
... else:
... return "Done"
...
>>> k=iter(fetch,"Done")
>>> k.next()
1
>>> k.next()
4
>>> k.next()
10
>>> k.next()
20
>>> k.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
Of course, this isn't a very useful application; Guido thought more of
something like
>>> f=open("/etc/passwd")
>>> k=iter(f.readline,"")
>>> k.next()
'root:x:0:1:Super-User:/:/sbin/sh\n'
> And again, there's no 'callable-iterator' type in types.
Sure is, it is called FunctionIterType. callable-iterator would not be
valid identifier...
Regards,
Martin
More information about the Python-list
mailing list