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


Groups > comp.lang.python > #32956

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

From Stefan Behnel <stefan_ml@behnel.de>
Subject Re: isinstance(.., file) for Python 3
Date 2012-11-08 16:14 +0100
References <2pjsm9-p8h.ln1@satorlaser.homedns.org> <XnsA1058E1707A9duncanbooth@127.0.0.1>
Newsgroups comp.lang.python
Message-ID <mailman.3443.1352387690.27098.python-list@python.org> (permalink)

Show all headers | View raw


Duncan Booth, 08.11.2012 14:58:
> Ulrich Eckhardt wrote:
>> 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?
> 
> Why bother checking types at all?
> 
> def foo(file_or_string):
>     try:
>         data = file_or_string.read()
>     except AttributeError:
>         data = file_or_string
>     ... use data ...

Or, a tiny bit more safely:

    try:
        read = file_or_string.read
    except AttributeError:
        data = file_or_string
    else:
        data = read()

I'd rather go with one of the previous solutions, though.

Stefan

Back to comp.lang.python | Previous | NextPrevious 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