Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #112013 > unrolled thread
| Started by | eryk sun <eryksun@gmail.com> |
|---|---|
| First post | 2016-07-29 11:59 +0000 |
| Last post | 2016-07-29 11:59 +0000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: TypeError: '_TemporaryFileWrapper' object is not an iterator eryk sun <eryksun@gmail.com> - 2016-07-29 11:59 +0000
| From | eryk sun <eryksun@gmail.com> |
|---|---|
| Date | 2016-07-29 11:59 +0000 |
| Subject | Re: TypeError: '_TemporaryFileWrapper' object is not an iterator |
| Message-ID | <mailman.22.1469793641.6033.python-list@python.org> |
On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
<antoon.pardon@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__ instead of
returning self, which would allow it to proxy the wrapped file's
__next__ method. There may be a good reason for that design decision,
but at the moment I don't see it, so I'd simply try the following:
import tempfile
import functools
class _TemporaryFileWrapper(tempfile._TemporaryFileWrapper):
def __iter__(self):
return self
def __next__(self):
return next(self.file)
@functools.wraps(tempfile.NamedTemporaryFile, assigned=['__doc__'])
def NamedTemporaryFile(*args, **kwds):
f = tempfile.NamedTemporaryFile(*args, **kwds)
f.__class__ = _TemporaryFileWrapper
return f
if __name__ == '__main__':
with NamedTemporaryFile('w+', prefix='tmptest-') as f:
for n in range(10):
f.write('This is line %d.\n' % n)
f.seek(0)
try:
while True:
print(next(f), end='')
except StopIteration:
pass
Back to top | Article view | comp.lang.python
csiph-web