isinstance(.., file) for Python 3

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Thu Nov 8 07:05:22 EST 2012


Hi!

I have two problems that are related and that I'd like to solve together.

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, while the built-in 
class file doesn't exist, so I can't use that code.

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 possible, I'm looking for a solution that works for Pythons 2 and 3, 
since I'm not fully through the conversion yet and have clients that 
might use the older snake for some time before shedding their skin.

Suggestions?

Uli





More information about the Python-list mailing list