isinstance(.., file) for Python 3

Chris Angelico rosuav at gmail.com
Thu Nov 8 13:57:00 CET 2012


On Thu, Nov 8, 2012 at 11:05 PM, Ulrich Eckhardt
<ulrich.eckhardt at dominolaser.com> 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...

Can you use the inverted check "isinstance(p, str)"? It's more likely
that you'll want to pass a file-like object than a string-like object.
This would work on Python 2 as well, though it's semantically
different; to safely check for both Unicode and bytes strings on both
Py2 and Py3, this may work:

# Once-off:
try:
    basestring
except NameError:
    basestring = (str, bytes)

# Is p a string?
if isinstance(p, basestring):
    pass

It abuses the fact that isinstance will happily accept the
'basestring' common supertype of both strings in Python 2, but will
equally happily accept a tuple of types.

ChrisA


More information about the Python-list mailing list