Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32946

Re: isinstance(.., file) for Python 3

References <2pjsm9-p8h.ln1@satorlaser.homedns.org>
Date 2012-11-08 23:57 +1100
Subject Re: isinstance(.., file) for Python 3
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3432.1352379430.27098.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

isinstance(.., file) for Python 3 Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2012-11-08 13:05 +0100
  Re: isinstance(.., file) for Python 3 MRAB <python@mrabarnett.plus.com> - 2012-11-08 12:54 +0000
  Re: isinstance(.., file) for Python 3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-11-08 12:56 +0000
  Re: isinstance(.., file) for Python 3 Chris Angelico <rosuav@gmail.com> - 2012-11-08 23:57 +1100
  Re: isinstance(.., file) for Python 3 Peter Otten <__peter__@web.de> - 2012-11-08 14:02 +0100
  Re: isinstance(.., file) for Python 3 Duncan Booth <duncan.booth@invalid.invalid> - 2012-11-08 13:58 +0000
    Re: isinstance(.., file) for Python 3 Stefan Behnel <stefan_ml@behnel.de> - 2012-11-08 16:14 +0100

csiph-web