Some libraries checking whether type of input f is file or not. And Python 2.7 library tempfile returns object in type file for
type(tempfile.TemporaryFile()) # type is file
And for
type(tempfile.NamedTemporaryFile()) # type is instance
Is there some reason or it is just a bug?
Read the documentation for NamedTemporaryFile:
The returned object is always a file-like object whose
file
attribute is the underlying true file object. This file-like object can be used in awith
statement, just like a normal file.
Looking at the implementation , both TemporaryFile
and NamedTemporaryFile
are actually factory functions. Depending on the OS, TemporaryFile
can simply returns a low-level file handle (on non-posix compliant systems and cygwin, TemporaryFile
is NamedTemporaryFile
). NamedTemporaryFile
always returns an instance of _TemporaryFileWrapper
, which is an old-style class (hence the 'instance'
) that wraps a low-level file handle.
I would not say that this is a bug (though, maybe qwirky due to the naming convention not following PEP8) as everything behaves according to the documentation -- After all, the returned values are file-like .
The problem I had with NamedTemporaryFile is that pylint complained that the result was not an iterable. Probably this is a bug in pylint.
#!/usr/bin/python
'''
Test program for pylint complaint about file-like object returned from
tempfile functions.
'''
import tempfile
cmdOut = tempfile.NamedTemporaryFile(prefix="tmp-scc-cmd-stderr")
print "Return value from NamedTemporaryFile() is %s" % type(cmdOut)
print >>cmdOut, "foo\nbar" # send two lines of output
cmdOut.seek(0) # go back to beginning to read output
for line in cmdOut:
print line.rstrip()
The reported type is 'instance'.
% python ~/perl/tempfile-pylint.py
Return value from NamedTemporaryFile() is <type 'instance'>
foo
bar
However pylint complains that
E: 14,12: Non-iterable value cmdOut is used in an iterating context (not-an-iterable)
I agree this isn't a bug in tempfile, but does create a bit of confusion in cases like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.