TypeError: '_TemporaryFileWrapper' object is not an iterator

eryk sun eryksun at gmail.com
Fri Jul 29 21:17:22 EDT 2016


On Fri, Jul 29, 2016 at 7:34 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 7/29/2016 7:59 AM, eryk sun wrote:
>>
>> On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
>> <antoon.pardon at rece.vub.ac.be> wrote:
>>>
>>> The problem seems to come from my expectation that a file
>>> is its own iterator and in python3 that is no longer true
>>> for a NamedTemporaryFile.
>>
>> For some reason it uses a generator function for __iter__
>
> This is a common idiom for having iterable.__iter__ return an iterator
> without writing and instanciating an iterator class.

Yes, using a generator function is a simple way to create multiple
iterators of an iterable, which is especially useful for a sequence
that's independently reiterable. However a Python io file is its own
iterator because it's based on a synchronous operating system File
that maintains a file pointer. (Python io files don't support Windows
asynchronous file access, which doesn't update the File pointer, and
even the low-level _winapi and _overlapped implementations don't
support this.)

In this case there's no point that I can see in using a generator
function for __iter__. If you call iter() again on the
tempfile._TemporaryFileWrapper, it doesn't produce a new iteration of
the underlying file until seek(0) is called to reset the file pointer.
So __iter__ may as well  return `self` and have __next__ proxy
next(self.file).



More information about the Python-list mailing list