isinstance(.., file) for Python 3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Nov 8 07:56:57 EST 2012


On Thu, 08 Nov 2012 13:05:22 +0100, Ulrich Eckhardt wrote:

> Firstly, I have code that allows either a file or a string representing
> its content as parameter. If the parameter is a file, the content is
> read from the file. In Python 2, I used "isinstance(p, file)" to
> determine whether the parameter p is a file. In Python 3, the
> returnvalue of open() is of type _io.TextIOWrapper, 

Incorrect.

py> type(open('x', 'wb'))
<class '_io.BufferedWriter'>

The type returned by open will depend on what you open and how you open 
it.

> while the built-in
> class file doesn't exist, so I can't use that code.

import io
file = io._IOBase

will probably work. But consider it a little smelly, since you're relying 
on an implementation detail.


> Secondly, checking for the type is kind-of ugly, because it means that I
> can't use an object that fits but that doesn't have the right type. In
> other words, it breaks duck-typing. This is already broken in the Python
> 2 code, but since I have to touch the code anyway, I might as well fix
> it on the way.

if hasattr(obj, 'read'):
    # object is file-like enough to treat as a file
    pass

That means that you can also use io.StringIO objects as pseudo-files too.



-- 
Steven



More information about the Python-list mailing list