isinstance(.., file) for Python 3

MRAB python at mrabarnett.plus.com
Thu Nov 8 13:54:15 CET 2012


On 2012-11-08 12:05, Ulrich Eckhardt wrote:
> 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?
>
Instead of checking whether it's a file, check whether it's a string!


More information about the Python-list mailing list